6

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.

PaulNUK
  • 4,774
  • 2
  • 30
  • 58
  • 1
    Yes and No... If you use Spring Boot 1.4 snapshot then you can have that, for simple cases only! earlier versions don't have that. (This ability was added in Spring 4.3). – M. Deinum Mar 07 '16 at 14:02
  • Thanks Martin, I'll carry on with setter injection until then. – PaulNUK Mar 07 '16 at 15:52

2 Answers2

5

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.

ben75
  • 29,217
  • 10
  • 88
  • 134
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();
  }      
}
SunLiWei
  • 1,313
  • 4
  • 11
  • 30