@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)
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.
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.
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.
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.
Since the release of Spring 4, the use of @Order
has been expanded to include @Component
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With