I'm in the process of moving some Xml-Based spring config over to Java-based.
Previously, I've consciously mixed Xml <bean class='foo' />
declarations with @Component
mappings on a case-by-case basis, as a means of documenting non-obvious beans.
A typical use case would be if I'm declaring beans that will modify the behaviour of spring itself, I'll declare these explicitly, rather than let them be discovered, purely to improve the clarity of the config file.
However, often these beans will need a degree of @Autowiring
. If I new
the bean up myself within a Java config, I become responsible for performing this wiring -- which is pointless.
Is there a pure Java configuration option that explicitly provides a class back to Spring, and let's it manage the instantiation?
ie:
Given the class:
public class MyFunkySpringBean implements InitializingBean {
@Autowired Foo foo;
}
In XML config, this would be declared as simply as:
<bean class="MyFunkySpringBean" />
Is there an equivalent in Java syntax, where I can explicitly declare the bean class to Spring, but not be responsible for providing the actual instance -- leaving that to Spring.
Eg:
@Configuration
public class MyAppConfig {
// Explictly provide the class, not the instance to Spring
@Bean
public MyFunkySpringBean funkyBean; // No instance -- it's up to Spring to build
}
To be clear, I don't want to have to do this:
@Configuration
public class MyAppConfig {
@Bean
public MyFunkySpringBean funkyBean() {
MyFunkySpringBean bean = new MyFunkySpringBean();
bean.foo = new Foo();
// other dependencies go here
return bean;
}
}
Does facility like this exist within Spring?
In newer versions of Spring (as of 4.2) you can use org.springframework.context.annotation.Import
e.g.
@Configuration
@Import(MyFunkySpringBean.class)
public class MyAppConfig {
... other config ...
}