Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which order does spring start beans?

I have two beans (class A and class B) defined in an XML file. When I start them, the DefaultListableBeanFactory creates the instance of class A first, then the instance of class B. Then I copy the classes into a separate package and make some minor modifications. When I start the classes from the new package, the DefaultListableBeanFactory creates the instance of class B first, then the instance of class A. Why did Spring change the initialization order? It doesn't seem to be random (i.e. in the old package always class A is started first, in the new package always class B is started first). I can (and probably should) add a "depends-on" tag to the definition of class B to ensure consistent start order, but I'd like to know why it worked in the old package.

like image 633
user2414208 Avatar asked Oct 13 '25 10:10

user2414208


1 Answers

Spring will use a ClassPathBeanDefinitionScanner to find all your beans and register them in a BeanDefinitionRegistry. Internally it will use a PathMatchingResourcePatternResolver. The beans will be added in the order they are discovered, and later, spring will iterate over them and load them in this order resolving the needed dependencies (see DefaultListableBeanFactory.preInstantiateSingletons).

The idea behind Spring mechanism is to hide from you all this stuff and guarantee a well constructed object graph in your application context as soon as your definitions are correct (Spring can instantiate your bean, Spring can resolve its dependencies ...)

From DefaultListableBeanFactory :

/** List of bean definition names, in registration order */
private final List<String> beanDefinitionNames = new ArrayList<String>(64);
like image 100
Alexandre Jacob Avatar answered Oct 15 '25 00:10

Alexandre Jacob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!