java 带有构造函数参数的 Autowire Bean
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35820833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Autowire Bean with constructor parameters
提问by george
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 I get the exception
我有一个带有构造函数参数的 bean,我想使用注释将其自动装配到另一个 bean 中。如果我在主配置中定义 bean 并在那里传递构造函数参数,那么它工作正常。但是,我没有主配置,而是使用 @Component 和 @ComponentScan 来注册 bean。我尝试使用 @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();
}
}
采纳答案by sisyphus
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.
for 的构造函数Bean
需要用@Autowired
or注释@Inject
,否则 Spring 将尝试使用默认构造函数构造它,而您没有其中之一。
The documentationfor @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.
该文档的@Autowired
说,它是用来标记一个构造函数,字段setter方法或配置方法,由Spring的依赖注入设施被装配。在这种情况下,您需要告诉 Spring 用于自动装配依赖项的适当构造函数不是默认构造函数。在这种情况下,您要求 Spring 创建SecondBean
实例,为此它需要创建一个Bean
实例。在没有带注释的构造函数的情况下,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