I have a bean created this way:
@Configuration
public class TestConfiguration {
@Bean
List<TestItem> testItemsList(TestItem item1, TestItem item2, TestItem item3) {
return List.of(item1, item2, item3);
}
}
I have this list autowired in other service.
@Service
public class ItemsServiceImpl implements ItemsService {
private final List<TestItem> testItems;
....
@Override
public Result useItems() {
testItems.forEach(item -> {
log.info("component: " item.toString());
});
}
The thing is, when I try to use it in a simple forEach
loop, the order is different, I get item3, item1, item2
logged.
I've also played with it a little bit and added a constructor:
public ItemsServiceImpl(List<TestItem> testItems) {
this.testItems = testItems;
log.info("constructor order" Arrays.toString(testItems.toArray()));
}
and it also prints the values in incorrect order: testItem3, testItem1, testItem2
.
What can be the issue here?
CodePudding user response:
You are not using the list created by the testItemsList
bean method. What you are given is a list of all TestItem
implementations by Spring. This is explained in this section of the Spring Reference Guide.
In fact your code would still work in the same way even if you would remove the testItemsList
method.
You have 2 ways to solve this.
- Add an
@Qualifier("testItemsList")
next to the@Autowired
annotation (or on the constructor). - Remove the
testItemsList
and place@Order
on yourTestItem
implementations for the order you want them in.