简体   繁体   中英

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

@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

@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 . 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?

Mmm.. i recommend to you use qualifiers to add your beans to the "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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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