Bozho
Bozho

Reputation: 597076

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

@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)

Upvotes: 13

Views: 6387

Answers (3)

lkatiforis
lkatiforis

Reputation: 6255

The accepted answer is invalid since Spring 4(JIRA ticket).

If you add @Order(1), @Order(2) to your bean definitions, they will be injected in a collection ordered according to the value parameter.

Upvotes: 0

code
code

Reputation: 4221

Since the release of Spring 4, the use of @Order has been expanded to include @Component

Upvotes: 4

axtavt
axtavt

Reputation: 242686

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);
}

Upvotes: 12

Related Questions