码迷,mamicode.com
首页 > 编程语言 > 详细

Spring中Bean初始化及销毁方法(InitializingBean接口、DisposableBean接口、@PostConstruct注解、@PreDestroy注解、以及init-method方法和destroy-method方法)

时间:2019-05-26 17:59:57      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:auto   sys   www   print   png   return   lap   回调   info   

一、
在Spring中Bean的初始化后以及销毁前的回调方式有:

  • init-method:是指创建bean时调用的方法,注意,不是创建bean的方法。
  • destroy-method:是指销毁bean时调用的方法,同样,不是销毁bean的方法。

  • @PostConstruct注解:在bean实例化和注入后,进行初始化
  • @PreDestroy:在bean销毁前回调

  • InitializingBean接口:
查看InitializingBean接口的源码可以发现,只有一个方法,需要pojo继承InitializingBean接口并实现afterPropertiesSet方法来在bean实例化和注入后初始化
public interface InitializingBean {
    void afterPropertiesSet() throws Exception;
}
  • DisposableBean接口:
查看DisposableBean接口发现只有一个方法destroy,需要pojo继承DisposableBean接口并实现destroy方法,在bean被销毁前进行回调
public interface DisposableBean {
    void destroy() throws Exception;
}

二、案例
Pojo类:

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class StudentA implements InitializingBean,DisposableBean{
    private String name;
    private String stuId;
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
        System.out.println("设值注入Name:"+name);
    }
    
    public String getStuId() {
        return stuId;
    }
    
    public void setStuId(String stuId) {
        this.stuId = stuId;
        System.out.println("设值注入stuId:"+stuId);
    }
    
    public StudentA(String name, String stuId) {
        super();
        this.name = name;
        this.stuId = stuId;
    }
    
    public StudentA() {
        super();
        // TODO Auto-generated constructor stub
        System.out.println("通过无参构造...StudentA实例化");
    }
    
    @Override
    public String toString() {
        return "StudentA [name=" + name + ", stuId=" + stuId + "]";
    }
    
    /**
     * 重写DisposableBean接口里的方法
     * 在销毁前回调
     */
    @Override
    public void destroy() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("DisposableBean接口的destroy()");
    }
    
    /**
     * 重写InitializingBean接口里的方法
     * 在实例化并设值注入后初始化回调
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("InitializingBean接口的afterPropertiesSet()");
    }
    
    /**
     * 自定义初始化后回调
     * 对应着bean里的init-method="start"
     */
    public void start() {
        // TODO Auto-generated method stub
        System.err.println("自定义初始化回调...init-method=\"start\"");
    }
    
    /**
     * 自定义销毁前回调
     * 对应着bean里的destroy-method="end"
     */
    public void end() {
        // TODO Auto-generated method stub
        System.out.println("自定义销毁回调...destroy-method=\"end\"");
    }
    
    /**
     * 通过@PreDestroy注解
     * 初始化后回调方法
     */
    @PostConstruct
    public void postConstruct(){
        System.out.println("初始化后回调方法...@postConstruct注解");
    }
    
    
    /**
     * 通过@PreDestroy注解
     * 销毁前回调方法
     */
    @PreDestroy
    public  void preDestory(){
        System.out.println("销毁前回调方法...@preDestory注解");
    }
    
}

applicationContext.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
        
        
        <!-- 如果想使用@ Resource 、@ PostConstruct、@ PreDestroy等注解就必须声明CommonAnnotationBeanPostProcessor -->
        <context:annotation-config/>
        
        <!-- 注册studentA对象 -->
        <bean class="com.pojo.StudentA" id="studentA" init-method="start" destroy-method="end">
            <!-- 设值注入 -->
            <property name="name" value="zsl"/>
            <property name="stuId" value="zsl33"/>
        </bean>
</beans>

测试:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.pojo.StudentA;

public class Test {
    @SuppressWarnings("resource")//去警告,问题不大不要慌
    public static void main(String[] args) {
        ClassPathXmlApplicationContext applicationContext = 
                new ClassPathXmlApplicationContext("applicationContext.xml");
        
        StudentA bean = (StudentA) applicationContext.getBean("studentA");
        System.out.println(bean);
        
        /**
         * 在非web环境下需要手动关闭IOC容器,则需调用registerShutdownHook()方法
         * 而web环境下已有相应的配置进行关闭IOC容器
         */
        applicationContext.registerShutdownHook();
    }
}

结果:
技术图片

三、执行顺序:
通过上面的案例和结果可以看出它们之间的执行顺序:

初始化时:
构造函数Construct ->属性注入 ->@PostConstruct ->InitializingBean接口 ->bean的init-method自定义的方法 
销毁时:@PreDestroy ->DisposableBean接口 ->bean的destoryMethod自定义的方法

Spring中Bean初始化及销毁方法(InitializingBean接口、DisposableBean接口、@PostConstruct注解、@PreDestroy注解、以及init-method方法和destroy-method方法)

标签:auto   sys   www   print   png   return   lap   回调   info   

原文地址:https://www.cnblogs.com/zhangsonglin/p/10926662.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!