Saturday, August 31, 2013

Modularising Spring's Java-based configuration

When using Spring's XML based configuration it is a good approach to modularise the configuration with the <import/> element. For example with a JPA repository configuration there can be an infrastructure configuration for setting up the LocalContainerEntityManagerFactoryBean and JpaTransactionManager

Using the above, not application specific configuration, we can create an application specific repository configuration

The above modularisation can be easily achieved also using Spring's Java-based configuration. The @Import annotation can import other configuration classes.

Besides @Import, the @ImportResource can be used to import configuration from XML files. You can mix the XML and Java configuration this way, although I do not recommend doing that. Similar to using XML or Java for DI configuration the my recommendation is that together with your team you decide which approach to use and stick to it, otherwise maintenance work will be much more difficult.

Note that Spring requires CGLIB to support Java configuration classes. Starting from Spring 3.2 explicit dependency on CGLIB is no longer required, because it is repackaged and inlined into the framework.

For a working example you can have a look at my github account.

No comments: