Question of lifycycle callbacks of beans in Spring

48 views Asked by At

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?

1

There are 1 answers

0
Ken Chan On

According to this :

A child bean definition inherits scope, constructor argument values, property values, and method overrides from the parent, with the option to add new values. Any scope, initialization method, destroy method, or static factory method settings that you specify override the corresponding parent settings.

So first of all , it only make sense to configure the init-method of the child bean if its init-method is different from the parent bean. If both child and parent beans has the same init-method , it is not necessary to configure the init-method on 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 :

public class Player extends Student{

   
  void init(){
     super.init();
     //do other player initialisation codes here..
  }

}

Otherwise , you can implement it as :

public class Player extends Student{

   
  void init(){
     //do player initialisation codes here..
  }

}