Home > Java > Consider replacing Spring XML configuration with JavaConfig

Consider replacing Spring XML configuration with JavaConfig

Spring articles are becoming a trend on this blog, I should probably apply for a SpringSource position :-)

Colleagues of mine sometimes curse me for my stubbornness in using XML configuration for Spring. Yes, it seems so 2000’s but XML has definite advantages:

  1. Configuration is centralized, it’s not scattered among all different components so you can have a nice overview of beans and their wirings in a single place
  2. If you need to split your files, no problem, Spring let you do that. It then reassembles them at runtime through internal tags or external context files aggregation
  3. Only XML configuration allows for explicit wiring – as opposed to autowiring. Sometimes, the latter is a bit too magical for my own taste. Its apparent simplicity hides real complexity: not only do we need to switch between by-type and by-name autowiring, but more importantly, the strategy for choosing the relevant bean among all eligible ones escapes but the more seasoned Spring developers. Profiles seem to make this easier, but is relatively new and is known to few
  4. Last but not least, XML is completely orthogonal to the Java file: there’s no coupling between the 2 so that the class can be used in more than one context with different configurations

The sole problem with XML is that you have to wait until runtime to discover typos in a bean or some other stupid boo-boo. On the other side, using Spring IDE plugin (or the integrated Spring Tools Suite) definitely can help you there.

An interesting alternative to both XML and direct annotations on bean classes is JavaConfig, a former separate project embedded into Spring itself since v3.0. It merges XML decoupling advantage with Java compile-time checks. JavaConfig can be seen as the XML file equivalent, only written in Java. The whole documentation is of course available online, but this article will just let you kickstart using JavaConfig. As an example, let us migrate from the following XML file to a JavaConfig




    
        
    

    
        
    

    
        
            
            	
            
        
    

The equivalent file is the following:

import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MigratedConfiguration {

    @Bean
    public JButton button() {

        return new JButton("Hello World");
    }

    @Bean
    public JButton anotherButton(Icon icon) {

        return new JButton(icon);
    }

    @Bean
    public Icon icon() throws MalformedURLException {

        URL url = new URL("http://morevaadin.com/assets/images/learning_vaadin_cover.png");

        return new ImageIcon(url);
    }
}

Usage is simpler than simple: annotate the main class with @Configuration and individual producer methods with @Bean. The only drawback, IMHO, is that it uses autowiring. Apart from that, It just works.

Note that in a Web environment, the web deployment descriptor should be updated with the following lines:


    contextClass
    org.springframework.web.context.support.AnnotationConfigWebApplicationContext


    contextConfigLocation
    com.packtpub.learnvaadin.springintegration.SpringIntegrationConfiguration

Sources for this article are available in Maven/Eclipse format here.

To go further:

  • Java-based container configuration documentation
  • AnnotationConfigWebApplicationContext JavaDoc
  • @ContextConfiguration JavaDoc (to configure Spring Test to use JavaConfig)
email
Send to Kindle
Categories: Java Tags: ,
  1. March 10th, 2013 at 22:56 | #1

    Any advantages of annotations over XML configuration, besides compile-time checks?

  2. March 11th, 2013 at 22:28 | #2

    @Anton Arhipov
    You need to use CGLIB (it enhances compiled bytecode)

  3. March 13th, 2013 at 08:07 | #3

    @Nicolas Frankel It doesn’t answer my question

  4. March 15th, 2013 at 22:30 | #4

    @Anton Arhipov
    I think you mean JavaConfig.

    IMO, JavaConfig is good for refactoring, and static type checking, and if you are developing a normal app or webapp I would suggest keep working with XML. If you are developing a framework or something like that, than JavaConfig looks more suitable for me. You can define interfaces for your java based configuration classes, and then you can override those bean creation methods with different impl having same configuration interface.

    Java based configuration has one disadvantage. It cannot handle circular dependencies as good as XML based configuration. Though circular dependency might probably be sign of a design flaw, sometimes you could not escape from it.

  5. Philippe Marschall
    March 18th, 2013 at 11:20 | #5

    I was quite fond of JavaConfig until Spring 3.2.1. Now Spring will automatically invoke #close() #close(boolean) and #shutdown() methods on your beans defined with @Bean even if they don’t have an @PreDestroy annotation with no way of turning this behavior of other than using XML.

  1. No trackbacks yet.