简体   繁体   English

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

[英]Spring autowiring bean with mixed constructor

I have two beans like this:我有两个这样的豆子:

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

@Component
class B {
     //..
}

How can I build A and have B autowired?如何构建 A 并自动装配 B? If I use new I won't get anotherBean's value, if I use autowiring I won't get number's value.如果我使用 new 我不会得到 anotherBean 的值,如果我使用自动装配我不会得到 number 的值。

Edit: The number is calculated at runtime, so I can't use @Value like answers suggested.编辑:这个数字是在运行时计算的,所以我不能像建议的答案一样使用@Value。

Make use of @Value and inject the number's value via property.利用@Value并通过属性注入数字的值。 Your ClassA should look something like你的ClassA应该看起来像

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

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

Edit (post additional condition of runtime value for number)编辑(发布数字运行时值的附加条件)

You can fetch the bean from BeanFactory.getBeans method as correctly pointed out by M.Deinum in comments.您可以从BeanFactory.getBeans方法中获取 bean,正如M.Deinum在注释中正确指出的那样。

I found this question today looking for an answer myself.我今天发现这个问题正在寻找自己的答案。 After some consideration, here's a solution I think I'm going with.经过一番考虑,这是我认为我要采用的解决方案。 Basically I'm baking the factory method into the bean's class.基本上,我将工厂方法烘焙到 bean 的类中。 This has the advantage of keeping the 'internal' dependencies (B in this example) all inside the 'A' class, and hidden from the caller, while still allowing prototype creation using a caller's runtime value.这样做的优点是将“内部”依赖项(在本例中为 B)全部保留在“A”类中,并且对调用者隐藏,同时仍然允许使用调用者的运行时值创建原型。 And it doesn't require yet another class file just for a factory method.并且它不需要另一个仅用于工厂方法的类文件。

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);
    }
  }
}

Then you can request a prototype bean instance while providing only the runtime value:然后你可以请求一个原型 bean 实例,同时只提供运行时值:

applicationContext.getBean(A.class, 1);

You need to annotate the desired constructor-to-be-used as @Autowired, among other ways you can find with a Google search.您需要将所需的要使用的构造函数注释为 @Autowired,以及您可以通过 Google 搜索找到的其他方法。 As for your issue with 'number', there are ways to use annotations to set parameter values as well, also not difficult to find with a Google search.至于您的“数字”问题,也有一些方法可以使用注释来设置参数值,通过 Google 搜索也不难找到。

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

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