Reputation: 1703
I'm interested in getting a list of beans from the Spring ApplicationContext
. In particular, these are Ordered
beans
@Component
@Order(value=2)
And I'm in some legacy code that is not Spring enabled, so I've manufactured a method to get the ApplicationContext
. For spring beans, I know I can do something like:
@Bean
public SomeType someType(List<OtherType> otherTypes) {
SomeType someType = new SomeType(otherTypes);
return someType;
}
But the ApplicationContext
only provides a method getBeansOfType
which returns an unordered map. I've tried getBeanNames(type)
but that also returns things unordered.
The only thing I can think of is to create a dummy class that just contains the List, create a bean for that dummy class and retrieve the ordered list:
public class DumbOtherTypeCollection {
private final List<OtherType) otherTypes;
public DumbOtherTypeCollection(List<OtherType) otherTypes) {
this.otherTypes = otherTypes;
}
List<OtherType> getOrderedOtherTypes() { return otherTypes; }
}
@Bean
DumbOtherTypeCollection wasteOfTimeReally(List<OtherType otherTypes) {
return new DumbOtherTypeCollection(otherTypes);
}
....
applicationContext.getBean(DumbOtherTypeCollection.class).getOrderedOtherTypes();
Just wish I could do better.
Upvotes: 3
Views: 5974
Reputation: 2322
Spring can autowire all beans of a type into list. In addition to this if your beans are annotated with the @Ordered
or if the beans implement the Ordered
interface, then this list will have all the beans ordered.(Spring reference)
@Autowired
docs:
In case of a Collection or Map dependency type, the container will autowire all beans matching the declared value type.
@Autowired
List<MyType> beans;
EDIT: Ordering using the built-in OrderComparator
For your external context call, in order to have your beans prioritized by their order you could take advandate of the built-in comparator:
org.springframework.core.annotation.AnnotationAwareOrderComparator(new ArrayList(applicationContext.getBeansOfType(...).values()));
Or
Collections.sort((List<Object>)applicationContext.getBeansOfType(...).values(),org.springframework.core.annotation.AnnotationAwareOrderComparator.INSTANCE);
Upvotes: 7