我有这样的spring-Bean类:
public class A{
@Autowired
private B b;
@Autowired
private C c;
@Autowired
private D d;
public A(){
}
public A(B b){
this.b = b;
}
}
我有一些spring-xml-bean配置文件来初始化B类,但我也有spring-java配置类来初始化A类,如下所示:
@Configuration
public AConfigurator(){
@Bean
public A create(){
B b = new B();
A a = new A(b); //I set specific B instance
return a; //my already set b property will be overried(with the bean B that has already been created in the spring context by another xml configuration) by the spring when autowiring the properties
}
}
我的问题是,当createmetods返回A时,即使属性已经设置,弹簧也会自动连接属性。它将覆盖已设置的b属性。我只想自动连接构造函数中未设置的属性。有可能在春天做吗?
我强烈建议重新考虑如何使用自动布线和注入来实现DI。你不应该让A
类知道任何关于DI的事情。允许在配置类中完成所有连接。您可以通过自动连接@Configuration
类中的依赖类来实现这一点。然后在CCD_ 3的构造函数中使用它们。这看起来像
A类:
public class A{
private B b;
private C c;
private D d;
public A(B b,
C c,
D d){
this.b = b;
this.c = c;
this.d = d;
}
}
然后在AConfigurator
类中构造它,如:
@Configuration
class AConfigurator {
@Autowired
private B b;
@Autowired
private C c;
@Autowired
private D d;
@Bean
public A create(){
return new A(b, c, d);
}
}