6. Combining configuration styles

JavaConfig can be used in conjunction with any or all of Spring's other container configuration approaches.

6.1. JavaConfig and XML

6.1.1.  Bootstrapping JavaConfig from XML with ConfigurationPostProcessor

You may desire or be required to use XML as the primary mechanism for configuring the container, but wish to selectively use @Configuration classes to define certain beans. For such cases, JavaConfig provides ConfigurationPostProcessor, a Spring BeanPostProcessor capable of processing @Configuration classes.

    <!-- first, define your individual @Configuration classes as beans -->
    <bean class="com.myapp.config.AppConfig"/>
    <bean class="com.myapp.config.DataConfig"/>

    <!-- be sure to include the JavaConfig bean post-processor -->
    <bean class="org.springframework.config.java.process.ConfigurationPostProcessor"/>

Then, bootstrap an XML ApplicationContext:

ApplicationContext context = new ClassPathXmlApplicationContext("application-config.xml");

The beans defined in AppConfig and DataConfig will be available via context. Configuring configurations

An added benefit that comes along with bootstrapping JavaConfig from XML is that the configuration bean instances are eligible, just as any other bean, for dependency injection:

    <!-- a possible "configurable configuration" -->
    <bean class="org.my.company.config.AppConfiguration">
        <property name="env" value="TESTING"/>
        <property name="monitoring" value="true"/>
        <property name="certificates" value="classpath:/META-INF/config/MyCompany.certs"/>
    <!-- JavaConfig post-processor -->
    <bean class="org.springframework.config.java.process.ConfigurationPostProcessor"/>

6.1.2.  Bootstrapping XML from JavaConfig with @ImportXml

The @ImportXml annotation is provided to support importing beans defined in XML into @Configuration classes.

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/>
        <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>

@AnnotationDrivenConfig // enable the @Autowired annotation
public class Config {
    // autowire the DataSource bean declared in datasource-config.xml
    @Autowired DataSource dataSource;

    public FooRepository fooRepository() {
        // inject the autowired-from-XML dataSource
        return new JdbcFooRepository(dataSource);

    public FooService fooService() {
        return new FooServiceImpl(fooRepository());
Regardless of the bootstrapping mechanism used - ConfigurationPostProcessor or @ImportXml - bean references may always be bi-directional. XML-defined beans may reference @Configuration-defined beans and vice-versa.