问题
If I have a Spring configuration class (i.e. a class annotated with @Configuration) can I use constructor injection ?
As it stands if I add one I get a no default constructor message, and if I add a default constructor it uses that rather than the overloaded one, which doesn't really help.
回答1:
There is a bug report about this limitation. It will be fixed with Spring 4.3.
Please note that another bug report (not fixed yet today fixed in 4.3-RC1) report a problem when using this very new feature and injecting generics in constructor of a @Configuration class.
回答2:
In Spring 4.3, you can use org.springframework.beans.factory.ObjectProvider
in @Configuration annotated class constructors to inject beans. for example:
@Configuration
public class SimpleBean {
private final InnerBean prop1;
public Simple Bean(ObjectProvider<InnerBean> innerBeanProvider) {
prop1 = innerBeanProvider.getObject();
}
}
来源:https://stackoverflow.com/questions/35845106/is-constructor-injection-possible-in-spring-configuration-classes