Home > Java > Integrate Spring JavaConfig with legacy configuration

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.

email
Send to Kindle
Categories: Java Tags: ,
  1. Greg
    November 12th, 2013 at 01:18 | #1

    No need use injected members, just use injected arguments instead

    public AnotherService anotherService(@Autowired FooDao fooDao) {

  1. No trackbacks yet.