我有这样的春豆课:
public class A{
@Autowired
private B b;
@Autowired
private C c;
@Autowired
private D d;
public A(){
}
public A(B b){
this.b = b;
}
}我有一些初始化B类的spring配置文件,但也有初始化A类的spring java配置类,如下所示:
@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
}
}我的问题是,当创建 metods返回A时,即使已经设置了属性,春季也会自动处理这些属性。它将覆盖已经设置的b属性。我只想自动处理构造函数中没有设置的属性。能在春天做吗?
发布于 2019-11-07 15:30:45
我强烈建议您重新考虑如何使用自动处理和注入来实现DI。您不应该允许类A知道任何有关DI的信息。允许在配置类中完成所有连接。您可以通过自动连接@Configuration类中的依赖类来实现这一点。然后在A的构造函数中使用它们。这看起来就像
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);
}
}https://stackoverflow.com/questions/58751449
复制相似问题