Alex Rivera | Logout

When injecting a list of beans, is the order in the list the same as the defined order of the beans

Asked 2010-12-30T21:32:50.923
13
@Service @Order(1)
public class FooService implements IService {..}

@Service @Order(2)
public class BarService implements IService {..}

Is it guaranteed that the order in the following list will always be {FooService, BarService}:

@Inject
private List<IService> services;

(same question goes for xml config)

Edit
Report

1 Answer

12

I guess no because @Order is not a general purpose annotation. From javadoc:

NOTE: Annotation-based ordering is supported for specific kinds of components only, e.g. for annotation-based AspectJ aspects. Spring container strategies, on the other hand, are typically based on the Ordered interface in order to allow for configurable ordering of each instance.

Also there are no occurences of org.springframework.core.annotation.Order and AnnotationAwareOrderComparator in the source of beans and context modules.

A simple way to make this behave as expected is:

@PostConstruct
public void init() {
    Collections.sort(services, AnnotationAwareOrderComparator.INSTANCE);
}
answered 2010-12-30T22:00:34.153

Your Answer