Blogs

SpringSource Blog

A Java configuration option for Spring

Rod Johnson

Thanks to our philosophy of pluggability and a lot of hard work in the implementation, the Spring IoC container (like most of the rest of Spring) is extremely flexible.

One point that is often missed is that Spring configuration need not be in XML, although the XML format is by far the most commonly used. Spring has its own internal metadata format in the form of the BeanDefinition interface and subinterfaces. The BeanFactory and ApplicationContext implementations that represent IoC container instances are powered by this Java metadata, and are quite separate from metadata parsing, which is normally performed by BeanDefinitionReader implementations.

The BeanDefinition metadata was not originally designed with the end developer in view. With Spring 2.0, NamespaceHandlers (classes that handle XML extension namespaces) generate BeanDefinition metadata, and we introduced the BeanDefinitionBuilder, with a fluent API to make this easier. But generating BeanDefinition metadata nevertheless remains in the realm of infrastructure coding, rather than something to do daily as you code business logic and define regular Spring beans.

Today I want to describe a new option for defining beans in Java code, which is targeted to end users (developers) rather than infrastructure providers. This is currently a milestone release add-on to the Spring core, but may make its way into Spring proper.

Let start with an example:

@Configuration
public class MyConfig {
   @Bean
   public Person rod() {
      return new Person("Rod Johnson");
   }

   @Bean(scope = Scope.PROTOTYPE)
   public Book book() {
      Book book = new Book("Expert One-on-One J2EE Design and Development");
      book.setAuthor(rod());  // rod() method is actually a bean reference !
      return book;
   }
}

The @Configuration annotation identifies this object as a special configuration class. Each @Bean method defines a bean. The name of the bean is the name of the method. It's possible to define additional aliases with the annotation, but its best to pick up the name from the method, rather than the annotation, as it means that the compiler can take care of ensuring ambiguity.

Beans are configured in Java code, using constructors, properties or arbitrary method calls. Note that a call to another bean method establishes a dependency from the "book" bean to the "rod" bean. But there are key advantages over instantiating objects in Java without framework support: for example:

  • Every @Bean is a Spring component and can take advantage of all Spring services, such as declarative transaction management
  • Every public @Bean method is added to the Spring container, so it's eligible for injection into other objects, JMX export and other benefits.
  • It fits smoothly into an existing Spring environment.

It may be easier to follow what is happening by comparing this with XML definitions to achieve the same result, which would look as follows:

<bean id="rod" class="Person" scope="singleton">
   <constructor-arg>Rod Johnson</constructor-arg>
</bean>

<bean id="book" class="Book" scope="prototype">
   <constructor-arg>Expert One-on-One J2EE Design and Development</constructor-arg>
   <property name="author" ref="rod"/>
</bean>

Although it is based on annotations, this Java config mechanism is unique in uses of annotations I've seen that annotations are not included in the core business logic, but in separate configuration classes. Effectively, it's a DSL for configuration. So it retains the non-invasive promise of Spring: you don't need to change your Java code to use it.

The configuration class is analogous to an XML bean definition file, and thus the @Configuration annotation contains some similar options to the the <beans> element, such as default autowire or lazy init. For example:

@Configuration(defaultAutowire = Autowire.BY_TYPE, defaultLazy = Lazy.FALSE)
public class DataSourceConfiguration  extends ConfigurationSupport {
}

The @Bean annotation allows options such as scope, and lazy init to be set locally, just as with the <bean> element. The default scope is Singleton, as with XML.

This style of Java configuration has some interesting characteristics. For example:

  • References (such as the reference to the "rod" bean in the example) survive refactoring; any good IDE provides great tool support.
  • Because configurations are Java classes, they can participate in inheritance relationships. For example, you could define a superclass that demands some abstract @Beans to be implemented in subclasses.
  • It creates a new visibility option. An @Bean method can be protected, it which case it benefits from the usual characteristics of the Spring component, but is not visible externally–that is it not injectable and cannot be obtained by calling getBean() on the IoC context.

My experience in showing this to people (for over a year now) is that they sometimes take a moment to grok it, but usually end up quite enthusiastic.

This is not intended as a replacement for Spring's XML format. Like Spring 2.0 extension namespaces–and use of properties files which has been possible since Spring 1.0–it's an additional option. Complex applications require multiple types of configuration and Spring aims to provide the best overall solution for configuration. We continue to explore additional forms of configuration.

You will typically mix use of Java and XML configuration. You can use any number of Java configuration classes in the same application context.

The following example uses an XML bean definition to define a MyConfig bean, as shown above, which can be injected like any normal bean. The ConfigurationPostProcessor processes all beans with @Configuration annotations, generating the necessary bean definitions.

<beans>

 <bean class="..MyConfig"/>

 <bean class="org.springframework.beans.factory.java.ConfigurationPostProcessor"/>

 <bean class="SomeRandomBean">
 	<property...
 </bean>
</beans>

You can of course have plain old bean definitions, like "SomeRandomBean" in this example, in the same XML. And you could build a context out of Java configuration and existing XML configurations.

Costin has also implemented a convenient application context that uses wildcarding to load classes from the classpath like this:

ApplicationContext oneConfig = new  AnnotationApplicationContext(SimpleConfiguration.class.getName());
ApplicationContext aBunchOfConfigs = new AnnotationApplicationContext("**/configuration/*Configuration.class");

Classes are examined using ASM, without loading them. In future releases we'll probably offer additional autodetection scenarios.

The release is here. Costin Leau is now the project lead. The code should be considered alpha quality. We include an example of a modified Spring Pet Store, but lessons will undoubtedly be learned from use on real projects.

Costin and I would love your feedback on this feature.

What will happen to this code? Well, it depends on you. It certainly needs feedback (suggestions welcome), and the full range of possibilities (and implementation refinements) will emerge through use in anger, with any technology. It's not currently on the roadmap, but could make its way into a future version of the Spring core if it sparks enough interest.

Also, it needs a snappy name. Suggestions welcome!


Although today is the first (alpha) release, this functionality has a surprisingly long history–well over a year. I had a mad fit of coding when attending a software summit in Crested Butte, Colorado in August 2005, with Mark Pollack and Aleks Seovic of the Spring.NET project. I remember writing a lot of code in the back of a Jaguar XJ8 while Aleks drove from the Great Sand Dunes to Denver. I probably needed to write code to take my mind off the danger. I think the genesis of the idea may have actually dated back to a conversation with Howard Lewis Ship at JavaOne 2005…

Sadly I haven't had time to do more than work on this in fits and starts since, so hadn't gotten it to the point where we could release it. Fortunately, Costin Leau, Spring Modules lead and general Spring guru, has had more time for Spring coding since he joined Interface21 early this year, and he's stepped up to take this forward.

The implementation doesn't require any modifications to the Spring core. As I said, the IoC container is highly flexible. In case you're interested, it treats the configuration object as a factory bean and each bean definition is backed by an instance factory method on that object: A mechanism that has been available since Spring 1.1. It does a little bytecode manipulation on the configuration instance, presently using CGLIB, to make sure that repeated calls to singleton scoped @Bean methods always return the same object.

Similar Posts

Share this Post
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • DZone
  • LinkedIn
  • Slashdot
  • Technorati
  • Twitter
 

110 responses


  1. Cool stuff! Although very similar features were possible with jacn for a while [1].

    Anyways, can you or Costin write up a paragraph about usage of ASM in Spring Framework for ASM's users page? [2]

    [1] http://jacn.sourceforge.net/
    [2] http://asm.objectweb.org/users.html


  2. This looks like a very interesting feature. I've seen people on the forums asking for this so it should be well received. I'm quite intrigued to see how people intend to use this. I appreciate this isn't a replacement for XML, but people can be quite polar about things like this. Interesting to see if people do go for a hyrid approach.

    The characteristics of Java configuration does raise some interesting points, specifically visibility. Can you do this in XML configured Spring (again seen it raised on the forums)?

    As for a name, Spring XJ8 – "Unleash the Jaguar in you" :)


  3. Hey Rod,

    Looks pretty neat. As a Groovy alternative checkout Grails' new BeanBuilder that is coming in Grails 0.4: http://grails.org/Spring Bean Builder

    It is kind of a Spring DSL for creating bean definitions and supports all of what the XML version offers unless I've missed something :-)

    Comments welcome!

    Cheers,
    Graeme


  4. Hmm link didn't work too well. Retry: http://grails.org/Spring Bean Builder


  5. Hi,
    It is almost the reason I started Spring-Annotation project (https://spring-annotation.dev.java.net/nonav/);
    Today night I`ll release the version 1.0.2 that will use the XML Schema option of spring 2.0 to enable the annotations reading (instead of another ApplicationContext implementation as the previous version).

    if you do not like the Spring-Annotation approach, you can at lease use the same same kind of XML Schema configuration to enable your annotation approach.

    look at one of the test cases:


    package net.java.dev.springannotation.annotation.beans;

    import net.java.dev.springannotation.annotation.Property;

    public class ParentBean {
    @Property(bean="scopeTest")
    private ScopeTestBean testProp;

    public ScopeTestBean getTestProp() {
    return testProp;
    }

    public void setTestProp(ScopeTestBean testProp) {
    this.testProp = testProp;
    }
    }

    import net.java.dev.springannotation.annotation.Bean;

    @Bean(name="parentTest")
    public class ParentPropertyBean extends ParentBean{
    }

    package net.java.dev.springannotation.annotation;

    import net.java.dev.springannotation.annotation.beans.ParentPropertyBean;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import junit.framework.TestCase;

    public class ParentPropertyTest extends TestCase {
    private ApplicationContext factory;

    protected void setUp() throws Exception {
    factory = new ClassPathXmlApplicationContext("classpath*:testContext.xml");
    }

    public void testParentProperty() {
    ParentPropertyBean bean = (ParentPropertyBean) factory.getBean("parentTest");
    assertNotNull(bean.getTestProp());
    }
    }
    -- the XML configuration --
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sa="https://spring-annotation.dev.java.net/context"
    xsi:schemaLocation="https://spring-annotation.dev.java.net/context https://spring-annotation.dev.java.net/nonav/context.xsd"
    default-autowire="byName">
    <sa:annotation-autoload/>
    </beans>

    I almost never use the @Property annotation, I prefer to just use the auto-wire approach …

    We have a lot of good code already written, the support for JSF is great and you have two more scopes already implemented for JSF applications (working in port it to Spring MVC).
    flash (from the end of one request to the start of the next one)
    and conversation (until a method with @ConvEnd is executed)

    please take a look and comment.


  6. I absolutely love the idea, I sometimes feel the need to have conditional logic in the xml configuration files, that solves that problem nicely. That fills the need I saw lacking in scripting support for configuration, I thought what was missing was the possibility to create your own bean and add them to the spring context. You annotation does that and goes even further.

    I have one question though, is it possible to get beans from the xml context injected in the annotation context? If so, what's he API to access that context, an abstract method annotated?


  7. Hi Guillaume.

    [quote post="101"]I have one question though, is it possible to get beans from the xml context injected in the annotation context? If so, what's he API to access that context, an abstract method annotated?[/quote]

    Yes that is indeed possible. Have a look at 'Chapter 4. Mixing XML and annotations' of the reference documentation. It comes down to calling ConfigurationSupport.getBean(beanName).


  8. Rod,

    Where I've seen Spring adoption retarded was around percieved need for "mass amount of XML configuration" with annotation being the new soup du jour. I've recieved a lot of feedback from customers who don't like the XML configuration (many end up living with it to get the other benefits of Spring). This is a great new tool. Thanks.

    Personally, I find the Spring XML configuration acceptable and not very error prone given the Spring IDE support and code completion (and when you compare to XML config for JSF, EJB, etc. it is extremely light). Yet….

    I know this is a feature I would use (and possible prefer over XML). If you combine this feature with the new Spring 2.0 sytle annoations for AOP, you could almost reduce the amount of XML configuration to nothing for a typical application.

    Have you looked at Spring Annotations? It is very Seam-ish and seems to provide another way to avoid "mass amounts of XML configuration".

    When will this support be in the core?
    When will "Spring Annotation" support be in the core?

    –Rick Hightower


  9. Rodrigo,

    Great stuff!

    [quote post="101"]It is almost the reason I started Spring-Annotation project (https://spring-annotation.dev.java.net/nonav/);
    Today night I`ll release the version 1.0.2 that will use the XML Schema option of spring 2.0 to enable the annotations reading (instead of another ApplicationContext implementation as the previous version).
    if you do not like the Spring-Annotation approach, you can at lease use the same same kind of XML Schema configuration to enable your annotation approach.[/quote]

    I looked into Spring Annotations after your post on TSS. I think Spring Annotations is one of the most innovative new features of Spring (or would be if it was in the official project). I just wish it was in the core. (I have not used it in anger yet so will withhold final judgement till I can bleed with it for a while.)

    I was shocked to see the cool reception you received from some of the Spring guys (okay just one) on TSS.

    I think your focus on providing Seam style support for Spring makes a lot of sense and is exactly what some of my customers have been looking for.

    I like the philosophy behind Spring Annotations, i.e., keeping simple things simple and not needing a lot of configuration.

    I am not sure I agree with all of the decisions (I am not sure I don't agree either). The docs seems a bit weak compared to what is available for Seam and Spring.

    There is still a lot to explore wrt to Spring Annotations. For example, can I override an annotation with an entry in the Spring app context file?

    –Rick Hightower


  10. Rick,
    [quote post="101"]I am not sure I agree with all of the decisions (I am not sure I don't agree either). The docs seems a bit weak compared to what is available for Seam and Spring.

    There is still a lot to explore wrt to Spring Annotations. For example, can I override an annotation with an entry in the Spring app context file?[/quote]
    there is plenty of room for changes in the project yet, and your opinion will be very welcome,
    in the today version (1.0.2) there is no way to override the annotations with XML, I`m researching a way to do this, but I want it included in the 1.1 version, this is a very important feature.

    I would thank you a lot if you could take a look at the few examples and docs in the site and contribute with some ideas.

    and I agree that there is too litle documentation today, I`m looking for help on this, but I have wrote a litle more docs and published it today.


  11. Nice stuff. It opens the door to many possibilities.
    I like the idea to keep the configuration stuff outside of the pojos. Also it makes refactoring easier and this is cool.
    It reminds me the code of the ServiceLocator I used to implement :-)

    Does this mean that you can add conditionnal code inside these Config classes. Isn't it a door left open to lots of hacky, unclean practices? Which is the exact contrary to the Spring spirit. (as in #configure in c/c , but here i am just tryin ti guess , as i do not know c/c … yes it is not good i know..)
    Another possibility could be to have theses config file replaced by some groovy code – which means a compromise between xml and java – with the advantages of dynamic languages, more possibilities to have loops or conditions, and yet something outside the code ie that can be tuned at deployment time/runtime.


  12. [quote post="101"]Does this mean that you can add conditionnal code inside these Config classes. Isn't it a door left open to lots of hacky, unclean practices?[/quote]
    I don't think that having conditional code inside this config classes would be hacky. Programming in XML is bad, but programming in Java is fine. I think that where you want conditional logic is probably an indication to use this approach.

    [quote post="101"]Another possibility could be to have theses config file replaced by some groovy code – which means a compromise between xml and java – with the advantages of dynamic languages, more possibilities to have loops or conditions, and yet something outside the code ie that can be tuned at deployment time/runtime.[/quote]
    Yes, a Groovy option certainly makes sense.


  13. This feature will solve the following problems:

    1. Too complex XML files can be replaced with simple factory classes. BTW. You could easly adopt your existing factories to function as spring contexts! This is cool! As a consequence most of the configuration simply disappears (someone already mentioned it…)

    2. If you need control over configuration, you don't have to use ( ugly in my opinion) bean factories, which where not intuitive – you can not be sure what the bean factory produces without looking at it's source. Also they seem to be seen as Spring-specific mechanism making your app strongly dependent on spring framework, which give me this strange feeling(smell) that it is one step too far.

    Personally I was fine with XML config files, but this feature will make developing Spring applications even easier!


  14. Piotr, I think you are spot on regarding the fact that this handles a number of scenarios very elegantly. For example, if you want to call arbitrary methods (not setters, constructors or init methods) with arguments that are injected or computed:

    @Configuration
    public class AConfiguration {
       private Dependency1 dep1;   // Setter omitted
       private Dependency2 dep2;   // Setter omitted
    private Dependency2 dep2;   // Setter omitted
    
       @Bean
       public SomeBean someBean() {
          SomeBean sb = new SomeBean();
          sb.callArbitraryMethod(dep1, dep2, System.currentTimeMillis());
          return sb;
       }
    }
    

    Regarding 2, I assume you mean FactoryBeans? Yes, this mechanism should solve some of the same problems. As you can dependency inject the @Configuration classes you can easily satisfy any dependencies you may need to populate the returned object.


  15. Oops, I accidentally submitted that and don't believe I can edit it. The code sample was incomplete. It should read:

    @Configuration
    public class AConfiguration {
       private Dependency1 dep1;   // Setter omitted
       private Dependency2 dep2;   // Setter omitted
       private Dependency3 dep3;   // Setter omitted
    
       @Bean
       public SomeBean someBean() {
          SomeBean sb = new SomeBean(dep1);
          sb.callArbitraryMethod(dep2, dep3, System.currentTimeMillis());
          return sb;
       }
    }
    

  16. [quote comment="2378"]
    Another possibility could be to have theses config file replaced by some groovy code – which means a compromise between xml and java – with the advantages of dynamic languages, more possibilities to have loops or conditions, and yet something outside the code ie that can be tuned at deployment time/runtime.[/quote]

    Scripting languages make a lot of sense. I tried plugging Groovy but unfortunately annotations are not yet supported by the Groovy compiler which means the metadata has to be read/stored differently.


  17. [quote comment="2390"][quote comment="2378"]
    Another possibility could be to have theses config file replaced by some groovy code – which means a compromise between xml and java – with the advantages of dynamic languages, more possibilities to have loops or conditions, and yet something outside the code ie that can be tuned at deployment time/runtime.[/quote]

    Scripting languages make a lot of sense. I tried plugging Groovy but unfortunately annotations are not yet supported by the Groovy compiler which means the metadata has to be read/stored differently.[/quote]

    My last message was disregarded as spam by the blog, maybe because I tried to post a tiny URL, but yes annotations are not supported by Groovy atm. However, they are not needed because of Groovy's meta programming model.

    Here is a snippet from the Grails runtime configuration engine that configures Spring Hibernate using a Groovy-Spring DSL:

    if(!dataSource) {
    hibProps."hibernate.hbm2ddl.auto" = "create-drop"
    }
    else if(dataSource.dbCreate) {
    hibProps."hibernate.hbm2ddl.auto" = dataSource.dbCreate
    }

    sessionFactory(ConfigurableLocalSessionFactoryBean) {
    dataSource = dataSource
    if(application.classLoader.getResource("hibernate.cfg.xml")) {
    configLocation = "classpath:hibernate.cfg.xml"
    }
    hibernateProperties = { MapToPropertiesFactoryBean b ->
    map = hibProps
    }
    grailsApplication = ref("grailsApplication", true)
    classLoader = classLoader
    }
    transactionManager(HibernateTransactionManager) {
    sessionFactory = sessionFactory
    }

    The method names translate to bean definition names, the first argument is the bean class. The closure at the end allows you to set properties on the bean. The full documentation can be found on the Grails website, but unfortunately the blog system here doesn't allow plus signs in URLs like those found in confluence wikis and when I post the link as a tinyurl it thinks it is spam.

    If you go to http://grails.org/Spring_Bean_Builder and replace the underscores with pluses you will see the rest of the docs. It is not tied to Grails and can be used standalone or as part of another application.


  18. Costin, I must add to that – although I like the idea of dynamic languages, it is quite natural to express the configuration in the language you are using for developent. This is the reason why I prefer java over XML in many cases. You can use refactoring, and easily reuse part of your configuration for testing, etc.

    I guess languages like groovy wont find much adoption until tools start supporting them. As far as I am concerned you can not debug Groovy.

    Look at AspectJ – it never really kicked off because of custom language. It has better chance now after introducing annotations. Even today I had a conversation with head of IT departament about it and he still thought it is not easy to debug AspectJ… (yes, I am proud, head of my departament still knows how to code :) )

    To summarize – Groovy as a configuration option yes, but not as a replacement for XML.


  19. Piotr

    [quote post="101"]It is quite natural to express the configuration in the language you are using for developent. This is the reason why I prefer java over XML in many cases. You can use refactoring, and easily reuse part of your configuration for testing, etc.[/quote]
    Indeed. These things are strengths of the Java approach.
    Rod


  20. I prototyped support for the Java configuration option as part of Spring IDE. I summarized my findings at http://springide.org/project/wiki/SpringJavaConfigurationOption.

    Let me know what you think of adding this to Spring IDE once the project is final.

    Christian


  21. Christian

    Wow–fast work! And I'm impressed that Spring IDE has such a solid base you can move forward so quickly…

    Rgds
    Rod


  22. I think a DSL implemented in a dynamic language is a viable option.
    I've just implemented a JRuby-based DSL for wiring up spring contexts (Springy).

    The above example could be expressed as follows:


    bean :rod, "Person" { |b| b.new("Rod Johnson") }
    bean :book, "Book", :scope=>"prototype" do |b|
    b.new("Expert One-on-One J2EE Design and Development").author(:rod)
    end

    However, as Piotr pointed out, no tool or refactoring support.


  23. [quote post="101"]Also they seem to be seen as Spring-specific mechanism making your app strongly dependent on spring framework, which give me this strange feeling(smell) that it is one step too far.
    Personally I was fine with XML config files, but this feature will make developing Spring applications even easier! [/quote]

    Hmmm…. The XML file was Spring specific as well. Now you can replace that with a Java configuration class. Either way you have one artifact (n artifacts really) that is Spring specific. As long as Spring does not bleed into the rest of your app what is the issue? The only difference really is I can express the configuration in XML or Java, I am not anymore more tied to Spring than I was before.

    I like the idea of expressing the configuration in Java. I can add some logic to the configuration (if needed on a limited basis). The more I think about this… the more I like it. When will it be in the core?


  24. One thing I would like to see added is support to return multiple objects, maybe by adding a @Beans annotation. We could use that for setting up queue listeners:

    @Beans
    public DefaultMessageListenerContainer createQueues() {
    String[] queueNames = new String[] { "queue1", "queue2", "queue3", … }
    DefaultMessageListenerContainer[] listeners =
    new DefaultMessageListenerContainers[queueNames.lenght];

    for (int i = 0; i

    For queues this approach is ok since listeners don't need to have a bean name, but maybe the project should provide a Bean class where in the constructor you can pass a name and an object (bean).

    And if I look at this code, maybe is makes more sense to create a template class for similar scenarios. Another question: is support planned for reading properties, doing JNDI lookups and lookup methods?

    Nice work.

    Steven


  25. I have been discussing a few other things with Rod. One idea I had is to handle very basic bean definitions where all you want is to specify the class, by using an abstract method, and letting the engine implement it, e.g.:

    @SimpleBean(scope = Scope.PROTOTYPE)
    abstract MyServiceImpl myService();

    At runtime this gets extended to return an instance of MyServiceImpl. So basically you do not have to type
    {
    return new MyServiceImpl();
    }

    and of course it's more concise, so hopefully also easier to read.

    Rod also suggested this mechanism could be used to alias beans from XML or another application context, so instead of having to use a call to
    ConfigurationSupport.getBean("myBean")

    to get and then inject an external bean called "myBean", you add an alias to an external bean via

    @ExternalBean(xxxxx)
    abstract MyBean myBean();

    and then to inject this just do a myBean() call. The nice thing is now you get type safety.

    Colin


  26. I think this is really great initiative. Especially for modularizing applications and building application components. This would allow to provide some public configuration for modules while keeping internal configuration private or protected. I missed such access control in the XML configuration.


  27. Christian, definitely, go for it! Though some markers on the left bar would be really handy and I hope these beans will be automatically shown in the Spring view.

    Comments are disabled in springide blog, so I hope you'll read this…


  28. I think this is gonna be a great addition! With emphasis of using this together with XML. Its definately is gonna make configuration a lot simpler. We could annotate stuff that are not expected to change (e.g. business services) and configure only environment dependent stuff in XML (e.g. data sources).

    The best of both worlds :) The only issue would probably be difficulty in locating the config (in XML or annotation)….but I guess that could quite easily be overcomed with proper organization.

    Looking forward to this being added to Spring Core!


  29. [quote comment="2395"]

    I guess languages like groovy wont find much adoption until tools start supporting them. As far as I am concerned you can not debug Groovy.

    To summarize – Groovy as a configuration option yes, but not as a replacement for XML.[/quote]

    You're right – scripting languages also have their downsides but they provide a simple and concise alternative to creating beans which is compelling.


  30. Steven

    [quote post="101"]One thing I would like to see added is support to return multiple objects, maybe by adding a @Beans annotation. We could use that for setting up queue listeners…[/quote]
    Interesting idea; I did consider supporting Maps at one point. It would not be easy to implement (as it's not just a factory method) but if it added sufficient value the effort would be worthwhile.

    [quote post="101"]And if I look at this code, maybe is makes more sense to create a template class for similar scenarios. Another question: is support planned for reading properties, doing JNDI lookups and lookup methods?[/quote]
    Yes. Good templates will make this very compelling, I think.

    Reading properties: Need to figure out an elegant way to support it
    JNDI lookups: Could be handled by a template or utility perhaps?
    Lookup methods: Not required in this approach.

    @Bean
    public void MyBean noNeedForLookupMethod() {
       return new MyBean() {
          @Override
          public void overrideWhatYouLike() {
          }
       };
    }
    

    Rgds
    Rod


  31. I've managed to compile the sources with maven2 but how do I run the tests?

    Also, the build.xml in the subversion repository is incomplete: Many libraries (all of spring plus the deps) are missing and the properties files build and project. Can you please commit them?

    Is there a mailing list for Spring JavaConfig?


  32. Rick
    [quote post="101"]The more I think about this… the more I like it. When will it be in the core?[/quote]
    It really depends on how many people get out there and kick the tyres and get feedback in. Once we're confident of the range of use cases and gather lessons learnt we can start to plan. It's not a huge amount of code (although the implementation is quite tricky), so there's no real obstacle to it going in the core in time.

    Rgds
    Rod


  33. [quote comment="2441"]I've managed to compile the sources with maven2 but how do I run the tests?

    Also, the build.xml in the subversion repository is incomplete: Many libraries (all of spring plus the deps) are missing and the properties files build and project. Can you please commit them?

    Is there a mailing list for Spring JavaConfig?[/quote]

    The project source code has been taken out of a private repo and there are still some loose ends (mainly the building process). I plan to take care of this in the very near future. There is a small README.TXT for the moment which indicates how the tests should be build (at the moment, some Spring test and sandbox classes are required).

    As for a mailing list, I would suggest to use the Spring forums (http://forum.springframework.org/).


  34. Very interesting approach with a lot of flexibility. I'm glad you guys are creating Spring support for this type of configuration :)

    The approach we've been using internally is done using a Java based DSL which looks a lot like the XML style (which people are familiar with). It's currently more limited in it's flexibility, but it makes for a straight forward transition from XML while giving you a fluent interface, code completion and refactoring support. It uses JDK 5 features and CgLib to do what it does.
    We're currently working on creating aop, jee, util, etc. DSL's to get easy configuration like in Spring 2.0 XML.

    Here's how a simple configuration file might look like:

    Configuration cfg = new Configuration("myConfig").using(new Registration() {
                @Override
                public void register() throws Exception {
                    PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = bean(PropertyPlaceholderConfigurer.class);
                    propertyPlaceholderConfigurer.setLocations(array(new ClassPathResource("jdbc.properties"), new ClassPathResource("other.properties")));
    
                    // ComboPooledDataSource is final
                    C3P0ComboPooledDataSourceWrapper dataSource = beanUsingWrapper("dataSource", ComboPooledDataSource.class, C3P0ComboPooledDataSourceWrapper.class,
                            lazyInit(), autoWire_No());
                    dataSource.setJdbcUrl("${jdbc.url}");
                    dataSource.setDriverClass("${jdbc.driverClassName}");
                    dataSource.setUser("${jdbc.username}");
                    dataSource.setPassword("${jdbc.password}");
                    destroyMethod(dataSource).close();
    
                    // Alternatively you can write attributes like this:
                    cfg(dataSource).lazyInit().autowire_No();
    
                    AnnotationSessionFactoryBean sessionFactoryBean = bean("sessionFactory", AnnotationSessionFactoryBean.class);
                    dependsOn(sessionFactoryBean, "org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect");
                    sessionFactoryBean.setDataSource(dataSource);
                    sessionFactoryBean.setConfigLocation(new ClassPathResource("hibernate.cfg.xml"));
                    sessionFactoryBean.setEventListeners(
                            map(
                               entry("merge", bean(IdTransferringMergeEventListener.class))
                            )
                    );
    
                    HibernateTransactionManager transactionManager = bean("transactionManager", HibernateTransactionManager.class);
                    transactionManager.setSessionFactory(ref("sessionFactory", SessionFactory.class));
    
                    AnnotationTransactionAspect transactionAspect = bean("transactionAspect", AnnotationTransactionAspect.class, factoryMethod("aspectOf"));
                    transactionAspect.setTransactionManager(transactionManager);
    
                }
    
            });
    
            GenericApplicationContext applicationContext = new GenericApplicationContext();
            cfg.toApplicationContext(applicationContext);
            applicationContext.refresh();
    

    /Jeppe


  35. Eugene, thanks for your feedback.

    What kind of information do you expect to get from the markers? Similiar to the approach Spring IDE uses for XML configuration files, we will not automatically detect annotated Java configuration classes right away. You can configure a specific class as a Spring IDE Config-using the preference page in the project's properties-and put it into a ConfigSet-together with other XML configuration files.

    If a Java configuration class is added, Spring IDE will display the defined beans in the Beans View and the Project Navigator.

    Christian


  36. JNDI injection could be done using yet further Annotations?

    @JNDI(lookup="/comp/env/myJndiObject")
    public abstract MyJndiObject getIt();

    And similar for Properties, maybe with built-in support for using Commons Configuration as the underlying provider (like what Spring Modules does)?


  37. Thomas,

    It doesn't make much sense to have tags that are that specialized. This would end up causing an explosion of tags. The whole point is these are supposed to be beans…

    But your example is not very verbose even handled normally

    @Bean
    public MyJndiObject myJndiObject() {
    return new JndiTemplate().lookup("java:comp/env/myJndiObject");
    }

    If the thing needs to be tweaked, then you can new the template and set properties separately.


  38. Jeppe

    What you describe is very very similar in concept to the first Java configuration approach I tried back in 2004–"recording" calls with CGLIB. (This code is probably still in the sandbox somewhere, unless someone has killed it.) I'd be interesting in discussing your experience, as real world usage is key to getting this ready for prime time.

    The recording approach certainly has many of the same advantages as the @Bean approach. However, I found that the reaction from folks (even the core Spring team) was a lot less positive to that style in general than the @Bean style…

    Rgds
    Rod


  39. Colin
    [quote post="101"]It doesn't make much sense to have tags that are that specialized. [/quote]
    I agree. The annotations should be conceptual, not implementation-specific. So the notion of an external property would certainly justify an annotation; JNDI is just one strategy for locating something, and that could lead to an explosion. Static factory methods might also be a good approach–more flexible than concrete inheritance from support classes that know about JNDI or something else environment-specific.
    Rgds
    Rod


  40. [quote comment="2510"]I'd be interesting in discussing your experience, as real world usage is key to getting this ready for prime time.[/quote]

    We've only been using it for about two months on two different projects, so I can only comment this far :)
    For starters people had to get used to the "magic" that happens. I found that this was more because they wanted to know what happens underneath, than it was something against the approach. Generic and varargs make it really easy to do this while avoiding unnecessary casts (I dunno if your implementation used generics?).
    The most annoying issue is with final classes, but we've handled that with wrappers (as in the example).

    We've used the CgLib method recording for other scenarios, such as UI component to model binding, and apart from having to perform the CgLib wrapping method call, bean(…) or bind(..), it has worked quite well and people have enjoyed working with it as it solves more problems than it creates. It allows them work with the Java API without having to adhere to a specific api (other than the wrapping) or resort to strings/xml or other approaches to solving this problem.

    /Jeppe


  41. Yes, I had toyed around with a similar idea. My Spring-less alternative was a two fold approach.

    Implement dependency injection as "your individual components get their dependencies injected externally" and "you have several classes/components which assemble smaller components and inject their dependencies".

    These "assembler" classes can be helped with what I call a "lazy-proxy". Your assembler looks exactly like your MyConfig class, sans annotations. But instead of instantiating it directly, you instantiate it via a Proxy factory which creates classes that implement MyConfig delegating to the actual MyConfig class, but maintaining a lazy cache (i.e. the result of the first rod() call is cached, subsequent calls return the cached object).

    The problem here is that you need interfaces, which can be annoying.

    OTOH, this allows you to have "configuration interfaces". At work, we split our configuration in lots of beans xml files. We also have alternative configurations (i.e. a JDBC DAO, an Hibernate DAO, etc.) which can be used; these "implement" some beans (i.e. both JDBC DAO and Hibernate DAO provide a "booksDAO" bean)- it would be nice to have a notion of Bean Config interface which specifies a set of beans that a bean.xml file must declare.


  42. Guys, just wanted to inform you that I've moved the project structure to maven2 so now compiling and running the tests should be straight forward.


  43. This is a very helpful feature. Our main context xml file is import of other xml files. We may go with a hybrid option and keep our main xml and replace other xml files with annotations. This may provide more static safety. Actually it is a matter of preference, and I always prefer annotation to xml.


  44. [quote comment="2408"]I have been discussing a few other things with Rod. One idea I had is to handle very basic bean definitions where all you want is to specify the class, by using an abstract method, and letting the engine implement it, e.g.:

    @SimpleBean(scope = Scope.PROTOTYPE)
    abstract MyServiceImpl myService();

    At runtime this gets extended to return an instance of MyServiceImpl. So basically you do not have to type
    {
    return new MyServiceImpl();
    }

    and of course it's more concise, so hopefully also easier to read.

    Rod also suggested this mechanism could be used to alias beans from XML or another application context, so instead of having to use a call to
    ConfigurationSupport.getBean("myBean")

    to get and then inject an external bean called "myBean", you add an alias to an external bean via

    @ExternalBean(xxxxx)
    abstract MyBean myBean();

    and then to inject this just do a myBean() call. The nice thing is now you get type safety.

    Colin[/quote]
    this are starting to look like the annotations from the Spring-Annotation
    Why don`t we just join forces to do some thing like this?
    I have a bunch of code writen to do this, and it is already working.


  45. [quote comment="2429"]I think this is gonna be a great addition! With emphasis of using this together with XML. Its definately is gonna make configuration a lot simpler. We could annotate stuff that are not expected to change (e.g. business services) and configure only environment dependent stuff in XML (e.g. data sources).

    The best of both worlds :) The only issue would probably be difficulty in locating the config (in XML or annotation)….but I guess that could quite easily be overcomed with proper organization.

    Looking forward to this being added to Spring Core![/quote]
    this is exactly what I use in the applications written with Spring-Annotation project …


  46. [quote comment="2488"]JNDI injection could be done using yet further Annotations?

    @JNDI(lookup="/comp/env/myJndiObject")
    public abstract MyJndiObject getIt();

    And similar for Properties, maybe with built-in support for using Commons Configuration as the underlying provider (like what Spring Modules does)?[/quote]
    why do not use the @Resource from the JSR 250 for it?


  47. Rodrigo
    [quote post=\"101\"]this are starting to look like the annotations from the Spring-Annotation
    Why don`t we just join forces to do some thing like this?[/quote]
    I think we are talking of fundamentally different mechanisms here. Spring Annotations, if I understand correctly, puts annotations in the main source code like JSR-250 and EJB3. The Spring Java configuration approach uses annotations in distinct configuration classes.
    [quote post=\"101\"]why do not use the @Resource from the JSR 250 for it?[/quote]
    @Resource performs a different role–to annotate a field or method in a business object, not an external configuration file. Of course it is relatively easy to implement JSR250 annotations on top of Spring. The Pitchfork project is an add-on to Spring that implements most of JSR-250 and EJB3 interception annotations. It was co-developed by Interface21 and BEA to underpin the Java EE 5 injection and interception features of WebLogic 10.

    Certainly if you are requiring annotations in business objects, I think converging on JSR250 makes sense, at least for basic needs. And as I mentioned, this has been available since June with Spring and Pitchfork.

    Rgds
    Rod


  48. [quote comment="2571"]
    I think we are talking of fundamentally different mechanisms here. Spring Annotations, if I understand correctly, puts annotations in the main source code like JSR-250 and EJB3. The Spring Java configuration approach uses annotations in distinct configuration classes.
    [/quote]
    Rod, I see your post is about an external configuration file …
    I was talking about the comments from Colin Sampaleanu, Thomas Timbul and Choon Whee …

    and using Pitchfork has one little problem …
    you still need to register all the beans in the applicationContext.xml they are not automatically recognized by spring just because they are annotated with @Session for example …
    this way you need to configure them twice what makes the things harder instead of easier.

    Rgds
    Urubatan


  49. How can I register a "dispose" method without forcing the bean to implement DisposableBean?

    Is there a forum for ongoing discussion like this somewhere?

    Very promising! Thanks!


  50. [quote comment="2589"]How can I register a "dispose" method without forcing the bean to implement DisposableBean?

    Is there a forum for ongoing discussion like this somewhere?

    Very promising! Thanks![/quote]
    don`t @PreDestroy solves your problem?
    or in XML destroy-method?


  51. [quote comment="2589"]How can I register a "dispose" method without forcing the bean to implement DisposableBean?[/quote]

    @Bean(destroyMethodName="whateverMethodIsCalled")
    

    I might also think about how to support custom callbacks that will destroy the object when the container shuts down.

    [quote comment="2589"]
    Is there a forum for ongoing discussion like this somewhere?
    [/quote]
    I would suggesting creating a thread in the Spring Forums (and posting the link here). Probably in Core Container.

    [quote comment="2589"]
    Very promising! Thanks![/quote]
    Thanks.


  52. [quote comment="2583"]
    and using Pitchfork has one little problem …
    you still need to register all the beans in the applicationContext.xml they are not automatically recognized by spring just because they are annotated with @Session for example …
    this way you need to configure them twice what makes the things harder instead of easier.
    [/quote]
    It is pretty straightforward to add automatic recognition of annotated classes to Pitchfork, and we intend to do so. The JavaConfig code actually includes an abstraction to do this, and has time allows we will provide an integration of this with Pitchfork.

    Rgds
    Rod


  53. [quote post="101"]It is pretty straightforward to add automatic recognition of annotated classes to Pitchfork, and we intend to do so. The JavaConfig code actually includes an abstraction to do this, and has time allows we will provide an integration of this with Pitchfork.[/quote]
    doing it Pitchfork will be almost what is already working with Spring-Annotation.
    but in spring-annotation we have already almost all the features from Seam, and a pretty good support for Convention over configuration for JSF applications …

    let me ask again, what do you think of joining forces to implement it?
    is there some problem with the approach Spring-Annotation uses to do it? I have asked it before by mail, and the response was that Spring does not like the "Dependency Lookup" of attaching annotations to the business classes, but if you are already planning to do it, I guess I can ask it again :D

    Thanks for the comments.


  54. In my opinion, this is a major improvement in the Spring configuration mechanism. In my company, we are in the process of porting our infrastructure to Spring and having over 300 bean definitions, even if the XML config is nice and simple to use (especially with the help of Spring IDE) that makes a lot XML to write and maintain so I can only see benefits on using a typed and compiled configuration.

    This being said, I looked at the actual implementation and some questions have arised:

    1) I see that only singleton and prototype scopes are supported. Is the full scope mechanism going to be used? (We are using request, session and custom scopes).

    2) The ConfigurationPostProcessor has its own internal cache for singleton. If we had a system configured with this mechanism, we would end up with duplicated caches contents (the Spring container itself and the configurator internal cache). Why not using the spring container itself?

    3) Default name used for a bean definition is the method name in the configuration class. This could easily lead to name collisions and unwanted bean overrides. I haven't thought about it very long but maybe the @Configuration annotation could have some extra parameters to define a naming scheme (possible schemes could be: (as it is right now), , … see what I mean?).

    I am very excited about this feature and am looking forward to using it! If this covers our needs, I really think about writing some XSL to convert most of our XML configurations to java classes…

    Very nice idea…

    Guillaume


  55. Oops… question 3) in my comment should have been:

    3) Default name used for a bean definition is the method name in the configuration class. This could easily lead to name collisions and unwanted bean overrides. I haven't thought about it very long but maybe the @Configuration annotation could have some extra parameters to define a naming scheme (possible schemes could be: MethodName (as it is right now), ConfigurationClassName.MethodName, FullyQualifiedConfigurationClassName.MethodName… see what I mean?).

    Guillaume


  56. Guillame

    Thanks for the thoughtful comments.
    [quote post="101"]1) I see that only singleton and prototype scopes are supported. Is the full scope mechanism going to be used? (We are using request, session and custom scopes).[/quote]
    The fact that only these scopes are supported reflects the fact that as I mentioned in my initial post, most of this code predates Spring 2.0. We need to update that side of it, and that's a good point.
    [quote post="101"]2) The ConfigurationPostProcessor has its own internal cache for singleton. If we had a system configured with this mechanism, we would end up with duplicated caches contents (the Spring container itself and the configurator internal cache). Why not using the spring container itself?[/quote]
    The references should be the same so that shouldn't matter. It may be possible to use the Spring cache and a getBean() call. The implementation definitely needs a thorough review and overhaul: basically at this point I want to validate the programming model before getting it fully up to Spring quality code.
    [quote post="101"]3) Default name used for a bean definition is the method name in the configuration class. This could easily lead to name collisions and unwanted bean overrides. I haven't thought about it very long but maybe the @Configuration annotation could have some extra parameters to define a naming scheme (possible schemes could be: MethodName (as it is right now), ConfigurationClassName.MethodName, FullyQualifiedConfigurationClassName.MethodName… see what I mean?).[/quote]
    This is a great idea. I have added support for overriding @Bean methods in XML in the SVN repo since the initial release.

    Rgds
    Rod


  57. This is great and will help me win arguments with spring-xmlphobes in management. call it the "Spring Bean Assembler".


  58. [quote post="101"]It doesn't make much sense to have tags that are that specialized.[/quote]

    Sorry my blatant ignorance (to be honest I haven't had a long start on annotations yet), but now I realise there is a more elegant way of doing it, and in fact that you can (and should) hide the implementation specific details in the configuration anyway (whichever means to configure you actually use).

    Still I am looking forward to being able to try this approach properly. It will allow core configuration to be built in to the core of the application, so when you release an 'update' there is no need to worry about configuration that clients may have changed…


  59. For a name how about Spring CoCo.
    Code Oriented Configuration
    Code based Configuration
    Configuration via Code

    You get the picture.


  60. One of the first computers I used was a Tandy Color Computer, which was widely known as "Coco" (http://en.wikipedia.org/wiki/TRS-80_Color_Computer). So that name has too much historical meaning to reuse more than twenty years later. :-)


  61. Very nice! A stylesheet to go from XML to Java would be nice! An annotation processor to go from Java to XML will close the loop. Way cool!


  62. [quote comment="5605"]One of the first computers I used was a Tandy Color Computer, which was widely known as "Coco" (http://en.wikipedia.org/wiki/TRS-80_Color_Computer). So that name has too much historical meaning to reuse more than twenty years later. :-) [/quote]

    Twenty years too late, thats not too bad, it was worth a try. You'll have to forgive my ignorance, it predates me by around eight months so I've never heard of it :-) .


  63. Axl
    [quote comment="6955"]Very nice! A stylesheet to go from XML to Java would be nice! An annotation processor to go from Java to XML will close the loop. Way cool![/quote]
    Interesting ideas–thanks! The annotation processor would be particularly nice I think.

    Rgds
    Rod


  64. It's great stuff! How does it work with beans that need properties that needs to be configured / managed separately?

    For example, in XML format, using PropertyPlaceholderConfigurer, one can externalize the database URL in a property file that can be separately managed:

    Maybe one can do it with some kind of annotation?
    @Bean
    @SpringProperty(name="jdbcUrl" value="${jdbc.url}")
    public DataSource c3p0DataSource() {
    return new com.mchange.v2.c3p0.ComboPooledDataSource();
    }


  65. The XML spring snippet for the above comments
    <bean id="c3p0DataSource"
    class="com.mchange.v2.c3p0.ComboPooledDataSource"
    destroy-method="close">
    <property name="jdbcUrl" value="${jdbc.url}" />


  66. Sam

    Currently there is no mature functionality for this in Java config, but it is on the list for future features. Of course it is possible to use an XML definition in such cases, riht now…

    Ideas welcome!

    Rgds
    Rod


  67. Very good job.

    This bean configuration allow to check errors on buildtime (like classcasting, false reference on a bean) or to refactor your code compared to xml configuration.


  68. Just a question.

    How it is possible in your example to get the instance of a bean without a getBean("book")?

    For example, I think it is important not to do something like

    Book book = (Book) factory.getBean("book");

    But something like

    Book book = myConfig.book();

    with myConfig equals to
    - something like new MyConfig() (with asm or aspect to get the instance, not a new bean)
    - or MyConfig.getInstance() (with dependency or with a beanlocator, not so cool).

    If it is possible, all errors on the Spring configuration (ClassCastException et NoSuchBeanDefinitionException when do getBean) are detectable on buildtime not on runtime. Refactoring will work anywhere.

    What do you think about that?


  69. "I guess languages like groovy wont find much adoption until tools start supporting them. As far as I am concerned you can not debug Groovy."

    Interesting, there is the same criticism against using XML for coding, and this from colleagues, but see the link below for similar opinions. So for example Hibernate and Spring make debugging extremely difficult. Thus perhaps the interest here.

    http://www.sdtimes.com/fullcolumn/column-20060901-05.html


  70. It's not as unique as it might look at first glance. Thats what I released in late 2005:

    http://annocon.sourceforge.net/

    Too bad, I hadn't had so much attention ;-)

    BTW: Why is the annotation called "Configuration" and not "Context" ?


  71. I didn't know http://annocon.sourceforge.net/ but conceptually, it is better than "Java configuration option for Spring" because the annotations are used to build the context but also get beans from the context. I think this fonctionnality is very important. Do you think you will develop this feature?


  72. Hi,

    I am looking for a tool/script to convert our existing XML files to Java configuration. Is there any one who write such a tool? I think I will need to refresh my XSLT knowledge.


  73. Hey, why do you remove my comments? I thought I was only giving feedback by talking about FactoryBeans.


  74. Caucus, I have not removed anyone\'s comments. But I did note some comments you made that have gone. I\'m puzzled. I\'ll try to find out what\\\'s going on.


  75. But where /is/ this add-on? The link on the original post links back to this same page. Can anyone point it to me? Thanks


  76. Sorry, found it :-) The first link was not correct though, and I missed the second near the last paragraphs.


  77. I think the beauty of the Spring IOC-Container is/was to encourage the
    dependency injection pattern.
    Using XML files unfortunately becomes harder and harder as the number of
    components we need to wire up grows. (And for a serious piece of software that typically is the case)
    Having said that and I think everybody would agree I would suggest to have a look at this blog I wrote a little while ago:

    http://weblogs.java.net/blog/unoinpiu/archive/2006/11/a_dynamic_langu.html

    just a suggestion … nothing more…


  78. Hmm, w/regards to missing comments, I do not have time to investigate now, but it may possibly be related to the comment spam filter. The filter (Spam Karma) can do something called "retrospanking", where a comment that is currently in moderation, moves to being considered outright spam, if the poster of that comment comes along and then posts some spammy comments, or does other suspicious activities (e.g. trying to post a lot of comments, or posting them very quickly, etc.). That said, I did not think this would ever apply to approved comments.


  79. Great initiative !!! And unmissable tool in the spring-core !
    Sincerely, I was very despite of the lack of Java config support in Spring 2.0
    At I21 you use to say that people are more open to XML config solution, but I don't think that they are Java developer's. As many guys said before, there is 2 level of configuration to address:
    1. Developement configuration (Java config)
    2. Infrastucture config (XML or Groovy like … )
    The Dev config is more general and give support to infrastructure config, deciding where to allow or not the override.
    Another aspect is that, the Java developement is more easy with Java5/6 features than java1.4 and less. So, for me, Spring 2.0 is more a support for old java programming, and that is good for all those who are stucked on java 1.4 or 1.3 for many legitime reasons, but very bad choice for those who could go up with new Java 1.5 projects.

    Today, I know that JEE5 have a big success, having take in his account the Spring idea in a new environment, and looking Spring as very complicated beacause of XML config. Don't forget that we are in a Java world and smart Developers want only one source tracking.

    So, It is time to split the future releases of Spring in 2 branchs:
    1. to support the old java style applications
    2. to support the new java specifications (JEE5 , EJB3 JAVA5/6)

    Don't miss the transition, because the actual JCL orientations are really in touch with the Java community, and they will get great advances (Remember Windows days, when Microsoft was calling to write code for the new windows platform, and others where saying they will do it when they will have more time …)
    It is appening again with the Java (JEE5 Java5/6 … ) have reached the top bar improvement where differenciation can be possible by simple adoption.

    IMHO, you guys at Spring, take care to focus on the right priorities.

    regards.


  80. [quote comment="10333"]I didn't know http://annocon.sourceforge.net/ but conceptually, it is better than "Java configuration option for Spring" because the annotations are used to build the context but also get beans from the context. I think this fonctionnality is very important. Do you think you will develop this feature?[/quote]

    up


  81. I totally agree with Claude B. Diesse.


  82. I also agree with Claude B. Diesse.

    What do you think about Guice (http://code.google.com/p/google-guice/)? It looks great !!!

    I think it is very important to improve the use of annotations in Spring.


  83. With some same ideas of guice, there is

    http://tapestry.apache.org/tapestry5/tapestry-ioc/index.html

    I'm a fan of Spring but I think it is urgent to propose a new annotation configuration in spring.


  84. This surely allows more flexibilty and will be very usefull. I think it would be nice to handle very basic bean definitions and inject that into any context (ApplicationConext, WebApplicationContext, etc..). Not sure if its already supported with spring annotation?


  85. I also agree that it's really necessary (and urgent) to extend Spring annotation configurability and to allow configuring evertyhing in Java (as a alternative to xml config, which BTW, I don't like). Configuring Spring MVC like that would be also good.

    Guice has really nice API and Spring shall also be extended with similar functionality.

    Spring javaConfig seems to be very slow in development. Last update of this project was in end of 11.2006. Does anyone still develop it? When will be first GA release?


  86. Grunch, Spring JavaConfig is anything but dead. I plan to spend more time on it in April and have a release out ASAP – probably end of April/May.


  87. I think if the name of a method annotated with @Bean getRod(), the bean id must be rod.

    After you can extract a Interface with getter method.

    The configuration class (@Configuration) implements this interface but you also create a configurable class (@Configurable) in order to inject dependencies automatically in your @Configurable class.

    You will use after the Configurable class in your code.

    All errors will be seen on build time.

    What do you think about this idea?


  88. On personal opinion, I find this very helpful.
    Guys, I have also posted some more relevant info further on this, not sure if you find it useful: http://www.bidmaxhost.com/forum/


  89. I was long awaiting this because:

    1) It enables automatic refactoring. When working with XML names of classes, names of properties, signatures of constructors tend to stay the same over development process — nobody wants to go and change XML along with java code!
    2) It enables type safety without additional efforts.

    What else could we dream of? Spring gets back to agile!
    My respect to the developers!


  90. I've used the Spring Annotations approach for some time and I like it. I've submitted some code to the project as well and blogged about how to use it.

    This is a little bit different as it relies in an external Java class that configures groups of beans together. It resembles a lot to the XML configuration. IMO it has the same advantages and flaws the XML has. It may be easier to read (for a Java developer) as XML is sometimes bloated but it doesn't offer too much beyond that.

    In the end I would be happier to see the @Bean applied to the actual POJO (the Spring Annotations project does it already) with a good (or better) way to handle dependencies (beyond autowiring) and scopes. I would love if the Spring people could commit some time to evaluate SA project/goals/work as it's really relevant.


  91. Hello

    Got an article that describes some of the time saving techniques with Spring MVC.

    http://coderslog.com/Convention_over_Configuration_for_Spring_MVC

    The site itself is a free non-profit resource for java developers working on large-scale projects.


  92. I’m currently working to get the Spring JavaConfig support into the 2.0 code stream. If everything goes well, you will see the support in one of the Spring IDE 2.0 nighty builds in a couple of days. We are planning to add preliminary support into Spring IDE 2.0 final.


  93. I've used the Spring Annotations approach for some time and I like it. I've submitted some code to the project as well and blogged about how to use it.


  94. Would be nice to see an update from I21 here.


  95. Cool job ! I really really like it and I want it !

    Question : If you want scripting language why not consider Bean Shell Scripting Framework instead of Groovy (I'm not a groovy enthusiast) ? I can't see any reason for BSH not to be the FIRST option.


  96. "A Java configuration option for Spring" – Good work. Cogratulations


  97. We are taking this project forward. Expect to see an M3 release this month.


  98. com.serv.IService

    com.serv.IService

    As shown in the above spring.xml for both 'Individual' and 'Oranization' id s I want to instantiate only the same class i.e, com.service.Service
    and I am repeating the entries unnecessarily. Can some body help me to make it as a single entry


  99. Vigrx plus is answer for your erectile dysfunction, anti impotence, enlargement, and hard rock erections. http://www.vig-rxplus.com


  100. JavaConfig is great, I love the type safety I get from building config in Java. I am extending ConfigurationSupport in one of my @Configuration-annotated classes and using getBean() to inject dynamically specified beans (ie, they are dynamically specified via a property file or command line parameter). So far, so good… but now I also want to be able to specify string-values that would normally run through Spring's registered Property Editors (without hooking back into XML-specified ). For example, maybe a new function called getProperty() similar to getBean() that maybe works like this:

    myNewBean.setEnumValue(
    (MyEnumClass)getProperty( "STRING_ENUM_TYPE", MyEnumClass.class ) );

    Maybe something to put on feature list?

    As for a catchy name, can I suggest "Coil" = "Configuring Objects In Language"? :)


  101. I am Very thank full the owner of this blog. Becouse of this blog is very imformative for me.. And I ask u some thiing You make more this type blog where we can get more knowledge.


  102. Excellent article. I've been using Spring for two years and it is fantastic


  103. Great initiative !!! And unmissable tool in the spring-core !
    Sincerely, I was very despite of the lack of Java config support in Spring 2.0
    At I21 you use to say that people are more open to XML config solution, but I don't think that they are Java developer's. As many guys said before, there is 2 level of configuration to address:
    1. Developement configuration (Java config)
    2. Infrastucture config (XML or Groovy like … )
    The Dev config is more general and give support to infrastructure config, deciding where to allow or not the override.
    Another aspect is that, the Java developement is more easy with Java5/6 features than java1.4 and less. So, for me, Spring 2.0 is more a support for old java programming, and that is good for all those who are stucked on java 1.4 or 1.3 for many legitime reasons, but very bad choice for those who could go up with new Java 1.5 projects.

    Today, I know that JEE5 have a big success, having take in his account the Spring idea in a new environment, and looking Spring as very complicated beacause of XML config. Don't forget that we are in a Java world and smart Developers want only one source tracking.

    So, It is time to split the future releases of Spring in 2 branchs:
    1. to support the old java style applications
    2. to support the new java specifications (JEE5 , EJB3 JAVA5/6)


  104. Nice stuff. It opens the door to many possibilities.
    I like the idea to keep the configuration stuff outside of the pojos. Also it makes refactoring easier and this is cool.
    It reminds me the code of the ServiceLocator I used to implement :-)


  105. This summer wear the to choose all kinds of shoes you need here.


  106. I m using this demo with Hibernate and Spring 3.0.2.
    I m getting error while deploying application .
    It,s jar files problem…
    Can i know which jar files i need to add..?


  107. Home Theater ProjectorJan 1, 2012 … The Top 10 Home Theater Projectors are broken into two resolution categories: 1080p and 720p. To help you find features important to you, …
    Cheap 1080P ProjectorFeb 27, 2008 … Certainly many people are jumping on the 1080p bandwagon these days because the price of projectors is ridiculously cheap. But now that …
    LCD Projector ScreenProjector Screens by Da-Lite Screens. Projector Screen specials that include free shipping. Over 3000 … Da-Lite Manual Model B Projector Screen 70" x 70" …
    Conference ProjectorJan 1, 2012 … Below are the Popular Conference Room Projectors for both small and large rooms. The major difference between these two groups is the …
    HID KitWelcome to HID Kits, the world's top retailer of HID lights & HID headlights. This week enjoy free shipping on all HID conversion kits, bulbs and ballasts within …


  108. The Nike LunarEclipse might look old school but they’re definitely new school and ready for your active lifestyle. The nike lunar shoes is considered Design for high performance and low environmental impact for traction and durability.


  109. Polo Ralph Lauren and Franklin & Marshall are both the famous brands in the world. The clothing fashioned from a durable, yet comfortable, woven cotton mesh that gets better with each washing. Welcome to the franklin marshall outlet online shop, where you can find the right outfit for you. You can get all kind of 2012 new style polo shirts in the ralph lauren uk outlet store,for example the 2012 london olympic ralph lauren polo.


  110. Hello, sir i would like to ask that what is the scope of java training, what all topics should be covered and it is kinda bothering me … and has anyone studies from this course http://www.wiziq.com/course/1779-core-and-advance-java-concepts of core and advance java online ?? or tell me any other guidance…
    would really appreciate help… and Also i would like to thank for all the information you are providing on java concepts.

18 trackbacks

Leave a Reply