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
You can impose ordering in your example by first eliminating static on the classes MyBean1
and MyBean2
, which when using Spring is not necessary in almost every case, as the default for Spring is to instantiate a single instance of each bean (similar to a Singleton).
The trick is to declare MyBean1
and MyBean2
as @Bean
and to enforce the order, you create an implicit dependency from bean1 to bean2 by calling bean2's bean initialization method from within bean1's initialization method.
For example:
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 {
interface MyBean{
default String printSimpleName(){
System.out.println(getClass().getSimpleName());
}
}
public class MyBean1 implments MyBean{
public MyBean1(){ pintSimpleName(); }
}
public class MyBean2 implments MyBean{
public MyBean2(){ pintSimpleName(); }
}
public class MyBean3 implments MyBean{
public MyBean3(){ pintSimpleName(); }
}
public class MyBean4 implments MyBean{
public MyBean4(){ pintSimpleName(); }
}
public class MyBean5 implments MyBean{
public MyBean5(){ pintSimpleName(); }
}
@Configuration
public class Config {
@Bean
MyBean1 bean1() {
//This will cause a a dependency on bean2
//forcing it to be created before bean1
bean2();
return addToAllBeans(new MyBean1());
}
@Bean
MyBean2 bean2() {
//This will cause a a dependency on bean3
//forcing it to be created before bean2
bean3();
//Note: This is added just to explain another point
//Calling the bean3() method a second time will not create
//Another instance of MyBean3. Spring only creates 1 by default
//And will instead look up the existing bean2 and return that.
bean3();
return addToAllBeans(new MyBean2());
}
@Bean
MyBean3 bean3(){ return addToAllBeans(new MyBean3()); }
@Bean
MyBean4 bean4(){ return addToAllBeans(new MyBean4()); }
@Bean
MyBean5 bean5(){ return addToAllBeans(new MyBean5()); }
/** If you want each bean to add itself to the allBeans list **/
@Bean
List allBeans(){
return new ArrayList();
}
private T addToAllBeans(T aBean){
allBeans().add(aBean);
return aBean;
}
}
public static void main(String[] args) {
new AnnotationConfigApplicationContext(Config.class);
}
}