I've got a bean with constructor parameters which I want to autowire into another bean using annotations. If I define the bean in the main config and pass in the constructor parameters there then it works fine. However, I have no main config but use @Component
along with @ComponentScan
to register the beans. I've tried using @Value
property to define the parameters but then I get the exception No default constructor found;
@Component
public class Bean {
private String a;
private String b;
public Bean(@Value("a") String a, @Value("b") String b)
{
this.a = a;
this.b = b;
}
public void print()
{
System.out.println("printing");
}
}
@Component
public class SecondBean {
private Bean bean;
@Autowired
public SecondBean(Bean bean)
{
this.bean = bean;
}
public void callPrint()
{
bean.print();
}
}
The constructor for Bean
needs to be annotated with @Autowired
or @Inject
, otherwise Spring will try to construct it using the default constructor and you don't have one of those.
The documentation for @Autowired
says that it is used to mark a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities. In this case you need to tell Spring that the appropriate constructor to use for autowiring the dependency is not the default constructor. In this case you're asking Spring to create SecondBean
instance, and to do that it needs to create a Bean
instance. In the absence of an annotated constructor, Spring will attempt to use a default constructor.
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With