【问题标题】:Autowire variable only if it was not set in constructor仅当未在构造函数中设置时才自动装配变量
【发布时间】: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 的属性,在构造函数中尚未设置。

标签: java spring


【解决方案1】:

我强烈建议您重新考虑如何使用自动装配和注入来实现 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);
    }
}

【讨论】:

  • 它的Spring 3应用程序,A是Spring在Spring自动扫描组件时创建的@Component,所以A类中的@_Autowired注解没有问题,我不能改变那个类.我只是试图找出是否可以在 Spring 中自动装配该属性,前提是该属性尚未在构造函数中设置并且为空。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-10
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
  • 1970-01-01
  • 2013-06-23
  • 1970-01-01
相关资源
最近更新 更多