Saturday 15 September 2012

How To Mix Spring XML And Java Configuration?

The @Configuration Spring annotation allows one to perform Spring configuration from Java (such as bean declaration for example). It is possible to implement a Spring application without any XML configuration (see here). It is even possible to get rid of the web application web.xml file too.

However, some Spring modules, such as the security module, still require plain XML configuration. Some applications may refer to old legacy code which has not been converted to Java configuration too.

In this case, one needs to mix Spring XML and Java configuration. This can be achieved with the @ImportResource Spring annotation:
@Configuration
@ImportResource({"classpath:/WEB-INF/spring-security.xml",
"classpath:/WEB-INF/legacy-config.xml"})
public class Config {

    @Bean
    MyBean MyBean() {
        return new MyBean();
    }

}
The above imports two XML files and declares a bean using Java.

More Spring related posts here.

2 comments:

  1. I was trying this, but I can't do that, can you publish an example?

    ReplyDelete
    Replies
    1. There is an example available here: http://technotes.tostaky.biz/2012/09/spring-security-and-annotation-example.html Cheers!

      Delete