【问题标题】:Spring: Choosing constructor while Autowiring a ComponentSpring:在自动装配组件时选择构造函数
【发布时间】:2017-05-05 10:11:33
【问题描述】:
我有一个组件如下:
@Component
class A(){
private s;
public A(){}
public A(String s){this.s=s;}
}
这是我自动连接上述类的另一个类:
@Component
class B(){
@Autowire
private A a;
}
在上面的自动装配中,我需要使用参数化的构造函数。如何传递构造函数参数?
【问题讨论】:
标签:
java
spring
javabeans
autowired
spring-bean
【解决方案1】:
你不能,至少不能通过B 中的@Autowired,但还有其他方法可以做到:
将参数连接到A的构造函数中:
一个构造函数用@Autowiredbecause注解:
从 Spring Framework 4.3 开始,@Autowired 构造函数不再是
如果目标 bean 只定义了一个构造函数,则需要。如果几个
构造函数可用,至少要注释一个才能教
它必须使用哪个容器。
@Component
class A(){
private s;
public A(){}
@Autowired
public A(@Value("${myval}") String s){this.s=s;}
}
将A 公开为@Bean
直接来自the docs:
@Configuration
public class AppConfig {
@Bean
public A a(@Value("${myval}") String s) {
return new A(s);
}
}
使用初始化回调在B 中构造A
Docs
@Component
class B(){
private A a;
@Value("${myval}")
private String myval;
@PostConstruct
private void init()
{
a = new A(myval);
}
}
【解决方案3】:
只需使用 setter 而不是构造函数。
如果你想用 new 关键字自己创建对象,那么这个对象将不会被容器管理。