Spring--Bean初始化和销毁前的操作顺序

Spring 允许在 Bean 在初始化完成后以及 Bean 销毁前执行特定的操作,常用的设定方式有以下三种:

  1. 通过Bean实现 InitializingBean/DisposableBean 接口来定制初始化之后/销毁之前的操作方法;【缺点:要依赖Spring】

  2. 通过 元素的 init-method/destroy-method属性指定初始化之后 /销毁之前调用的操作方法;(也可以不是xml配置,而是在@Bean上注解,效果相同)【优点:不依赖于Spring的接口】

  3. 在指定方法上加上@PostConstruct 或@PreDestroy 注解来制定该方法是在初始化之后还是销毁之前调用【在servlet中,要考虑的执行流程是:servlet构造函数 > PostConstruct > init() > service() > destory() > PreDestroy】

注意:子类实例化过程中会调用父类中的@PostConstruct方法!

但他们之前并不等价。即使3个方法都用上了,也有先后顺序.

Bean在实例化的过程中:Constructor > @PostConstruct >InitializingBean > init-method
Bean在销毁的过程中:@PreDestroy > DisposableBean > destroy-method
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class InitAndDestroySeqBean implements InitializingBean,DisposableBean {

    public InitAndDestroySeqBean(){
        System.out.println("执行InitAndDestroySeqBean: 构造方法");
    }
    
    @PostConstruct
    public void postConstruct() {  
       System.out.println("执行InitAndDestroySeqBean: postConstruct");  
    }  
    
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("执行InitAndDestroySeqBean: afterPropertiesSet"); 
    }
    
    public void initMethod() {
        System.out.println("执行InitAndDestroySeqBean: init-method");
    }

    @PreDestroy
    public void preDestroy()  {
        System.out.println("执行InitAndDestroySeqBean: preDestroy");
    }
    
    @Override
    public void destroy() throws Exception {
        System.out.println("执行InitAndDestroySeqBean: destroy");
    }
    
    public void destroyMethod() {
        System.out.println("执行InitAndDestroySeqBean: destroy-method");
    }
    
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("com/chj/spring/bean.xml");
        context.close();
    }
}


  
 
     
   
   

你可能感兴趣的:(Spring--Bean初始化和销毁前的操作顺序)