How to register collection of beans with application context and make eligible for autowiring?

1.5k Views Asked by At

I would like to create dynamic list of Spring managed beans in my @Configuration annotated AppConfig:

@Bean
List<SomeObject> createSomeObjects(@Value("${object.count}") final int objectCount) {

    List<Object> objects = new ArrayList<>();
    for (int i = 1; i <= objectCount; i++) {
        objects.add(new SomeObject())
    }
    return objects;
}

Then, I would like to inject this List of objects into another bean like this:

@Autowired
List<SomeObject> objects;

What I am getting is the following exception:

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: java.util.List ..

I could create some sort of container for my object list, but am looking for a more elegant solution.

3

There are 3 best solutions below

0
On BEST ANSWER

Spring handles collections specially, and this just doesn't work; the container always interprets a collection as the group of individually declared beans. After some discussion and modifications it will work in 4.3, but for now, the best solution is to use a holder class.

4
On

Since Spring 4, generics are fully supported during autowiring. So just update your Spring version and it should work.

If you can't update, just autowire by bean name:

@Bean(name = "someObjectsList")
List<SomeObject> createSomeObjects(@Value("${object.count}") final int objectCount) {

    List<Object> objects = new ArrayList<>();
    for (int i = 1; i <= objectCount; i++) {
        objects.add(new SomeObject())
    }
    return objects;
}

@Autowired
@Qualifier("someObjectsList")
List<SomeObject> objects;
0
On

Your solution should be no problem but your method,that creates the bean seems not to be public, so it may not be visible outside of the configuration class. see Chapter 3. Bean Visibility