简体   繁体   English

在 Spring 配置中自动装配/注入一个类型的单个 bean 和一个类型的 bean 列表的 bean

[英]Auto-wiring/injection of Individual beans of a type and bean of list of beans of a type in Spring Configuration

I have following set up in my spring configuration我在 spring 配置中进行了以下设置

@Bean
public Myclass myClassOne() {
    return new MyClass();
}

@Bean
public Myclass myClassTwo() {
    return new MyClass();
}

@Bean
public YourClass processAndCreateYourClass(List<MyClass> allMyclasses) {
    //Some business logic to process all myclasses beans so that I can create YourClass bean
     return new YourClass();
}

This works as expected and I get a list of all myclasses injected in processAndCreateYourClass (without autowired annotation) BUT what If I have one more bean like following这可以按预期工作,并且我得到了在processAndCreateYourClass中注入的所有 myclasses 的列表(没有自动装配注释)但是如果我还有一个像下面这样的 bean 怎么办

@Bean
public List<Myclass> listOfMyClasses() {
    //return list of my classes from here
}

in processAndCreateYourClass method I was expecting union of all individually declared myclass beans and list returned by listOfMyClasses .processAndCreateYourClass方法中,我期待所有单独声明的 myclass bean 和listOfMyClasses返回的列表的联合。 But that doesn't seem to be the case.但情况似乎并非如此。 Is it fair to expect that behavior from Spring or there is better elegant solution for this?期望 Spring 的行为是否公平,或者有更好的优雅解决方案?

Mmm.. i recommend to you use qualifiers to add your beans to the "processAndCreateYourClass".嗯..我建议您使用限定符将您的 bean 添加到“processAndCreateYourClass”。

Something like this will have maintainability and easy to read.像这样的东西将具有可维护性且易于阅读。

@Bean
public YourClass processAndCreateYourClass(@Qualifier("myClassOne") Myclass1, @Qualifier("myClassTwo") Myclass2) {
    //Some business logic to process all myclasses beans so that I can create YourClass bean
     return new YourClass();
}

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

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