繁体   English   中英

具有混合构造函数的 Spring 自动装配 bean

[英]Spring autowiring bean with mixed constructor

我有两个这样的豆子:

@Component
@Scope("prototype")
class A {
    A(int number, B anotherBean) {
         //...
    }
}

@Component
class B {
     //..
}

如何构建 A 并自动装配 B? 如果我使用 new 我不会得到 anotherBean 的值,如果我使用自动装配我不会得到 number 的值。

编辑:这个数字是在运行时计算的,所以我不能像建议的答案一样使用@Value。

利用@Value并通过属性注入数字的值。 你的ClassA应该看起来像

@Component
@Scope("prototype")
class A {

    @Autowired
    A(@Value("${some.property}")int number, B anotherBean) {
       //...
    }
}

编辑(发布数字运行时值的附加条件)

您可以从BeanFactory.getBeans方法中获取 bean,正如M.Deinum在注释中正确指出的那样。

我今天发现这个问题正在寻找自己的答案。 经过一番考虑,这是我认为我要采用的解决方案。 基本上,我将工厂方法烘焙到 bean 的类中。 这样做的优点是将“内部”依赖项(在本例中为 B)全部保留在“A”类中,并且对调用者隐藏,同时仍然允许使用调用者的运行时值创建原型。 并且它不需要另一个仅用于工厂方法的类文件。

public class A {

  private A (int number, B otherBean) {
  ...
  }

  @Configuration
  public static class BeanConfig {

    @Autowired
    private B otherBean;

    @Bean
    @Scope("prototype")
    public A makeA(int number) {
      return new A(number, otherBean);
    }
  }
}

然后你可以请求一个原型 bean 实例,同时只提供运行时值:

applicationContext.getBean(A.class, 1);

您需要将所需的要使用的构造函数注释为 @Autowired,以及您可以通过 Google 搜索找到的其他方法。 至于您的“数字”问题,也有一些方法可以使用注释来设置参数值,通过 Google 搜索也不难找到。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM