Is it possible to set order of instantiation in Spring?
I don't want to use @DependsOn
and I don't want to use Ordered
interface. I just need an order of instantiation.
The following usage of @Order
annotation does not work:
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
/**
* Order does not work here
*/
public class OrderingOfInstantiation {
public static class MyBean1 {{
System.out.println(getClass().getSimpleName());
}}
public static class MyBean2 {{
System.out.println(getClass().getSimpleName());
}}
@Configuration
public static class Config {
@Bean
@Order(2)
public MyBean1 bean1() {
return new MyBean1();
}
@Bean
@Order(1)
public MyBean2 bean2() {
return new MyBean2();
}
}
public static void main(String[] args) {
new AnnotationConfigApplicationContext(Config.class);
}
}
Beans are still instantiated in lexicographic order.
Why it does not work here?
Can I rely of lexicographic order anyway?
UPDATE
I would like any solution allowing to provide order of creation.
The goal is to populate collections at config level in correct order. Depends on
-- does not match the task. Any "explanations" on why Spring does not like to have ordered instantiations -- also does not match the task.
Order means order :)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…