仅在未在构造函数中设置的情况下才自动装配变量

我有这样的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 时,即使已设置属性,弹簧也会自动连接属性。它将覆盖已经设置的 b 属性。我只想自动装配在构造函数中未设置的属性。春季有可能吗?

anhuihaidong 回答:仅在未在构造函数中设置的情况下才自动装配变量

我强烈建议您重新考虑如何使用自动接线和注入来实现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://www.f2er.com/3143823.html

大家都在问