Spring documentation describes that beans managed by Ioc container are implicitly pre-instantiated by default other than specifying them as being lazy-initialized. I define a child bean definition A which inherits the configuration data from its parent bean definition B. Both of them have an attribute specified on the element. Then I retrieved an instance of bean A through the Ioc container and I found the Ioc container just called the bean A initialization method. Why the Ioc container didn't call the initialization method of bean B which was instantiated at startup?
<bean id="student" class="com.ford.spring.pojo.Student" lazy-init="true" init-method="init">
<property name="age" value="20"/>
<property name="gender" value="male"/>
<property name="name" value="porro"/>
<property name="id" value="1"/>
</bean>
<bean id="player"
class="com.ford.spring.pojo.Player"
parent="student" init-method="init" destroy-method="destroy">
<property name="nationality" value="Italy"/>
</bean>
ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext("config-metadata.xml");
Player player = (Player) applicationContext.getBean("player");
applicationContext.close();
System.out.println(player);
Why the Ioc container didn't call the initialization method of bean B which was instantiated at startup?
According to this :
So first of all , it only make sense to configure the
init-methodof the child bean if itsinit-methodis different from the parent bean. If both child and parent beans has the sameinit-method, it is not necessary to configure theinit-methodon the child bean.Second, whether the initialisation method will execute its parent initialisation method or not is its implementation details which from the bean definition point of view , it does not care about it. It only care you tell it what is the initialisation method such that it will simply execute it after it creates a bean instance and that 's it.
So if you want
Player's initialisation method to execute its parent 's init. method , you can implement it as :Otherwise , you can implement it as :