Java and XML configuration are not exclusive - both can be used inside the same Spring application. In order to retrieve a bean from an XML file, one has to use the Spring container. As mentioned, one can achieve this with @ExternalBean annotation (the recommended way). For cases where this is not suitable or desired, the underlying beanFactory used for the @Configuration class can be access. Out of the box, this can be achieved by extending configuration classes from ConfigurationSupport or by implementing the BeanFactoryAware interface.
Consider the following XML configuration:
<bean id="myBean" class="MyBean"/>
In order to refer to myBean bean when using Java, one can use the following snippets:
@Configuration
public class MyConfig extends ConfigurationSupport {
@Bean
public ExampleBean anotherBean() {
ExampleBean bean = new ExampleBean("anotherBean");
bean.setDep(getBean("myBean")); // use utility method to get a hold of 'myBean'
return bean;
}
}@Configuration
public class MyOtherConfig implements BeanFactoryAware {
private BeanFactory beanFactory;
public void setBeanFactory(BeanFactory beanFactory) {
// get access to the owning bean factory
this.beanFactory = beanFactory;
}
@Bean
public ExampleBean yetAnotherBean() {
ExampleBean bean = new ExampleBean("yetAnotherBean");
bean.setDep(beanFactory.getBean("myBean")); // use dependency lookup
return bean;
}
}Again, please consider twice before using ConfigurationSupport and/or BeanFactoryAware as @ExternalBean offers the same capability in a refactoring friendly manner.
JavaConfig distribution contains a converted Petclinic sample that replaces some XML configuration parts, with Java and Groovy - please see the samples folder for more info.