Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

spring

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

like image 747
Bozho Avatar asked Dec 30 '10 21:12

Bozho


People also ask

How do you inject two beans in the same class?

Using Java Configuration In this approach, we'll use a Java-based configuration class to configure multiple beans of the same class. Here, @Bean instantiates two beans with ids the same as the method names and registers them within the BeanFactory (Spring container) interface.

How do you inject multiple beans in spring?

You can add @Qualifier to your beans to distinguish between the different beans. When injecting the beans you can use the specified qualifier to inject the right one. Save this answer.

How do you inject a bean into a collection?

Using @Qualifier to Select Beans. We can use the @Qualifier to select the beans to be injected into the specific collection that matches the @Qualifier name.

What is the order of bean creation in spring?

The order in which Spring container loads beans cannot be predicted. There's no specific ordering logic specification given by Spring framework. But Spring guarantees if a bean A has dependency of B (e.g. bean A has an instance variable @Autowired B b; ) then B will be initialized first.


2 Answers

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

like image 134
code Avatar answered Nov 15 '22 22:11

code


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);
}
like image 36
axtavt Avatar answered Nov 15 '22 22:11

axtavt