/ JAVACONFIG, SPRING

Integrate Spring JavaConfig with legacy configuration

The application I’m working on now uses Spring both by parsing for XML Spring configuration files in pre-determined locations and by scanning annotations-based autowiring. I’ve already stated my stance on autowiring previously, this article only concerns itself on how I could use Spring JavaConfig without migrating the whole existing codebase in a single big refactoring.

This is easily achieved by scanning the package where the JavaConfig class is located in the legacy Spring XML configuration file:

<ctx:component-scan base-package="ch.frankel.blog.spring.javaconfig.config" />

However, we may need to inject beans created through the old methods into our new JavaConfig file. In order to achieve this, we need to autowire those beans into JavaConfig:

@Configuration
public class JavaConfig {

    @Autowired
    private FooDao fooDao;

    @Autowired
    private FooService fooService;

    @Autowired
    private BarService barService;

    @Bean
    public AnotherService anotherService() {
        return new AnotherService(fooDao);
    }

    @Bean
    public MyFacade myFacade() {
        return new MyFacade(fooService, barService, anotherService());
    }
}

You can find complete sources for this article (including tests) in IDEA/Maven format.

Thanks to Josh Long and Gildas Cuisinier for the pointers on how to achieve this.

Nicolas Fränkel

Nicolas Fränkel

Developer Advocate with 15+ years experience consulting for many different customers, in a wide range of contexts (such as telecoms, banking, insurances, large retail and public sector). Usually working on Java/Java EE and Spring technologies, but with focused interests like Rich Internet Applications, Testing, CI/CD and DevOps. Also double as a trainer and triples as a book author.

Read More
Integrate Spring JavaConfig with legacy configuration
Share this