【发布时间】:2019-11-07 14:59:00
【问题描述】:
我有这样的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;
}
}
我有一些初始化 B 类的 spring xml bean 配置文件,但我也有初始化 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
}
}
我的问题是,当 create 方法返回 A 时,即使已经设置了属性,spring 也会自动装配属性。它将覆盖已经设置的 b 属性。我只想自动装配未在构造函数中设置的属性。春天可以做吗?
【问题讨论】:
-
DI时不要使用 new,这是此模式的目标,以避免使用 new -
如果组件中只有 1 个构造函数,它会自动自动装配。也许尝试向您的 A 类添加第二个构造函数,看看这是否解决了问题。如果有,请告诉我,我们可以从那里拿走。
-
我完全同意@YCF_L ...要么使用 DI 框架,要么不使用。这就像驾驶波音 737 并让自动驾驶仪运行,同时还试图自己控制事物。可能不会有好的结局......
-
@YCF_L spring 配置类中 new 没有错。 B 不是spring Bean,不一定要被spring 拦截。另一方面,A 是 spring Bean,它是通过 spring 配置类创建的。
-
@Pete 当我写问题时,我忘了把默认构造函数放在那里。我添加了默认构造函数,但它并没有解决问题。我的问题是是否可以在 Spring 中仅自动装配为 null 的属性,在构造函数中尚未设置。