【问题标题】:Is constructor injection possible in Spring configuration classes?Spring 配置类中是否可以进行构造函数注入?
【发布时间】:2016-03-07 13:31:27
【问题描述】:

如果我有一个 Spring 配置类(即使用 @Configuration 注解的类),我可以使用构造函数注入吗?

如果我添加一个,我会收到一条没有默认构造函数的消息,如果我添加一个默认构造函数,它会使用它而不是重载的构造函数,这并没有真正的帮助。

【问题讨论】:

  • 是和否...如果您使用 Spring Boot 1.4 快照,那么您可以拥有它,仅适用于简单的情况!早期版本没有。 (此功能是在 Spring 4.3 中添加的)。
  • 谢谢 Martin,我会继续使用 setter 注入直到那时。

标签: spring constructor configuration constructor-injection


【解决方案1】:

有一个关于此限制的bug report。它将在 Spring 4.3 中修复。

请注意another bug report今天尚未修复已在 4.3-RC1 中修复)在使用这个非常新的功能并在 @Configuration 类的构造函数中注入泛型时报告了一个问题。

【讨论】:

    【解决方案2】:

    在 Spring 4.3 中,您可以在 @Configuration 注解的类构造函数中使用 org.springframework.beans.factory.ObjectProvider 来注入 bean。例如:

    @Configuration
    public class SimpleBean {
      private final InnerBean prop1;
      public Simple Bean(ObjectProvider<InnerBean> innerBeanProvider) {
         prop1 = innerBeanProvider.getObject();
      }      
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 2014-10-30
      • 2017-11-04
      • 1970-01-01
      相关资源
      最近更新 更多