【问题标题】:Spring Java Config reference in bean constructor to get other bean in constructed classbean构造函数中的Spring Java Config引用以获取构造类中的其他bean
【发布时间】:2016-10-24 10:50:39
【问题描述】:

我已经看到其中一个 bean 的构造函数中引用了 MyConfig(Spring 配置文件)的程序之一,以获取在 MyConfig 中定义的其他 bean。 我不确定这种配置。我可以在这种代码中看到循环引用,虽然它工作正常,但我无法理解流程。它是如何工作的。以下是该代码的副本 -

@Configuration
public class MyConfig {

   @Bean(name="a")
   @Scope("prototype")
   public A getA() {
      return new A();
   }

   @Bean(name="b")
   @Scope("prototype")
   public B getB() {
      return new B();
   }

   @Bean(name="c")
   @Scope("prototype")
   public C getC() {
      return new C();
   }

   @Bean(name="queueListener")
   @Scope("singleton")
   public Queue getQueue() {
      return new Queue(MyConfig config);
   }

}

这是我的队列类 -

public class Queue implements MessageListener{

    private MyConfig config;

    public Q(MyConfig config) {
       this.config = config;
    }

    @Override
    public void onMessage() {
       createC();
    }

    public void createC() {
       C cObj = config.getC();
       cObj.setConfig(config);
       cObj.performTask();
    }
}

类是“C”看起来像这样-

public class C{

   private transient MyConfig config;
   private MyConfig config;

   public C() {    
   }

   public void setConfig(MyConfig config) {
      this.config = config;
   }

   public MyConfig getConfig() {
      return config;
   }

   public void performTask() {     
      A a = config.getA();  // Is it right way to get bean?
      B b = config.getB(); 
   }

} 

所以我的问题是,在另一个 bean 中获取 bean 是正确的方法吗? 返回对象真的会是spring bean对象还是简单的java类对象?

我可以在上面的代码中看到循环引用,因为当在 MyConfig 中创建 Queue 类的实例时,将采用 MyConfig 的实例/引用。 这会创建循环引用吗? 我的架构师建议我使用上述方法,而不是在 Queue 类和“C”类中使用 autoWiring Application 上下文。根据架构师的上下文非常繁重,这不是最佳实践。

创建 bean Queue 时的执行周期或调用层次结构是什么? 了解上述代码的工作原理将非常有帮助。

【问题讨论】:

    标签: spring dependency-injection spring-java-config


    【解决方案1】:

    将配置实例注入特定的 bean 是一个非常糟糕的主意。它会使您的代码复杂化,并且不方便进行测试,因为要测试 Queue 实例,您应该以某种方式模拟整个配置。

    如果你想将一个原型 bean 注入到单例中,你可以使用这里描述的技术: Howto generate prototype objects with in a singleton bean using spring java configurations

    【讨论】:

      【解决方案2】:

      请参阅Spring Boot @Autowired creating instances on a runtime 的示例 您可以了解如何正确使用单例和原型

      【讨论】:

      • 鼓励链接到外部资源,但请在链接周围添加上下文,以便您的其他用户了解它是什么以及为什么存在。始终引用重要链接中最相关的部分,以防目标站点无法访问或永久离线。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      • 2011-04-06
      • 1970-01-01
      • 2013-05-26
      • 2011-09-14
      相关资源
      最近更新 更多