简体   繁体   English

带有构造函数参数的 Autowire Bean

[英]Autowire Bean with constructor parameters

I've got a bean with constructor parameters which I want to autowire into another bean using annotations.我有一个带有构造函数参数的 bean,我想使用注释将其自动装配到另一个 bean 中。 If I define the bean in the main config and pass in the constructor parameters there then it works fine.如果我在主配置中定义 bean 并在那里传递构造函数参数,那么它工作正常。 However, I have no main config but use @Component along with @ComponentScan to register the beans.但是,我没有主配置,而是使用@Component@ComponentScan来注册 bean。 I've tried using @Value property to define the parameters but then I get the exception No default constructor found;我试过使用@Value属性来定义参数,但后来出现异常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. Bean的构造函数需要使用@Autowired@Inject进行注释,否则 Spring 将尝试使用默认构造函数构造它,而您没有其中之一。

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. @Autowired文档说它用于将构造函数、字段、setter 方法或配置方法标记为由 Spring 的依赖注入设施自动装配。 In this case you need to tell Spring that the appropriate constructor to use for autowiring the dependency is not the default constructor.在这种情况下,您需要告诉 Spring 用于自动装配依赖项的适当构造函数不是默认构造函数。 In this case you're asking Spring to create SecondBean instance, and to do that it needs to create a Bean instance.在这种情况下,您要求 Spring 创建SecondBean实例,为此它需要创建一个Bean实例。 In the absence of an annotated constructor, Spring will attempt to use a default constructor.在没有带注释的构造函数的情况下,Spring 将尝试使用默认构造函数。

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM