Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autowire Bean with constructor parameters

Tags:

java

spring

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();
    }
    
}
like image 413
george Avatar asked Mar 05 '16 22:03

george


1 Answers

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

like image 82
sisyphus Avatar answered Sep 28 '22 10:09

sisyphus