Warren M. Nocos Warren M. Nocos - 19 days ago 8
Java Question

Spring Dependency Injection: Injection of all beans of type X as a Collection

I am wondering if it is possible for Spring's dependency injection framework to inject all beans of type

X
, like storing them all in a
Collection
.

Suppose I have this class:

public class Person {

protected String name;

public Person(String name) {
this.name = name;
}

// Setters and getters

}


And consider this configuration:

@Configuration
public class XxxxConfiguration {

@Bean
public Person janePerson() {
return new Person("Jane");
}

@Bean
public Person warrenPerson() {
return new Person("Warren");
}

@Bean
public Person katrinaPerson() {
return new Person("Katrina");
}

}


And suppose I am going to inject all
Person
objects in a component class for an instance, can I use
Collection
to imply that I am expecting all objects of that type?

For example:

@Service
public class XxxXxxxServiceImpl implements XxxXxxxService {

protected final Collection<Person> persons;

@Inject
public XxxXxxxServiceImpl(Collection<Person> persons) {
this.persons = persons;
}

// implemented service operations

}

Answer

The current code already works, but you can use @Order to load the Person objects at specific index into the list as shown below:

@Configuration
public class XxxxConfiguration {

    @Bean
    @Order(1)//janePerson will be at 0th index of list
    public Person janePerson() {
        return new Person("Jane");
    }

    //changed the order here 2 to 3
    @Bean
    @Order(3)//warrenPerson will be at 3nd index of list
    public Person warrenPerson() {
        return new Person("Warren");
    }

    @Bean
    @Order(2)//katrinaPerson will be at 2nd index of list
    public Person katrinaPerson() {
        return new Person("Katrina");
    }

}

You can refer here