Method called when spring initializes a bean and destroys a bean

Method called when spring initializes a bean and destroys a bean

 

three methods

 

1. Implement the operations performed before initializing and destroying beans through @PostConstruct and @PreDestroy methods

2. By defining init-method and destruction-method methods in xml

3. Implement InitializingBean and DisposableBean interfaces through beans

 

 

The execution order of the three ways:

1. Annotate first,

2. Then execute the method defined in the InitializingBean or DisposableBean interface,

3. Finally execute the method specified by the init-method or destroy-method attribute

 

 

For example: init-method and destroy-method given to xml

 

xml:

<bean id="personService" class="com.myapp.core.beanscope.PersonService" scope="singleton"  init-method="init"  destroy-method="cleanUp">  
  
</bean>  

 

Java:

package com.myapp.core.beanscope;  
  
  
public class PersonService  {  
   private String  message;  
  
    public String getMessage() {  
        return message;  
    }  
      
    public void setMessage(String message) {  
        this.message = message;  
    }  
     
  
      
    public void init(){  
        System.out.println("init");  
    }  
    //  how  validate the  destory method is  a question  
    public void  cleanUp(){  
        System.out.println("cleanUp");  
    }  
}  

 

Test class:

package com.myapp.core.beanscope;  
  
import org.springframework.context.support.AbstractApplicationContext;  
import org.springframework.context.support.ClassPathXmlApplicationContext;  
  
public class MainTest {  
  public static void main(String[] args) {  
        
      AbstractApplicationContext  context =new  ClassPathXmlApplicationContext("SpringBeans.xml");  
      
    PersonService  person = (PersonService)context.getBean("personService");  
      
    person.setMessage("hello  spring");  
      
    PersonService  person_new = (PersonService)context.getBean("personService");  
      
    System.out.println(person.getMessage());  
    System.out.println(person_new.getMessage());  
    context.registerShutdownHook();  
  
      
}  
}   

 

result:

init

hello  spring

hello  spring

cleanUp

It can be seen that the init method and the clean up method have been executed.

 

Notice:

context.registerShutdownHook(); is a hook method, which is called when the jvm closes and exits. In the template mode of the design mode, it is implemented by the implementation class by defining such a hook method in the abstract class. The implementation class here is the AbstractApplicationContext, which is how the spring container shuts down gracefully.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326529238&siteId=291194637