Spring has a default rule:Always initialize the main bean and then initialize the dependent bean.
In most cases, dependencies between beans are very direct. Spring containers inject bean dependencies before returning bean instances. If bean a depends on bean B, the spring container will automatically initialize bean B when the program requests bean A, and then inject bean B into Bean, finally, bean a with complete dependencies is returned to the program.
In extreme cases, dependencies between beans are not direct enough. For example, if another bean is used in the initialization block of a class, Spring always initializes the main Bean first. When the initialization block is executed, the main bean is not instantiated, and the dependent bean is not instantiated yet. In this case, an exception is thrown.
You can useDepends-on
Attribute, which can be forced to initialize one or more beans before initializing the main bean.
<Bean id = "beanone" class = "examplebean" depends-on = "manager"> <property name = "manager" ref = "manager"/> </bean> <Bean id = "manager" class = "managerbean"/>