zoukankan      html  css  js  c++  java
  • Spring bean初始化与销毁的几种方式和区别

    1. <bean> 元素的 init-method/destroy-method属性指定初始化之后 /销毁之前调用的操作方法

    2. 指定方法上加上@PostConstruct 或@PreDestroy注解来制定该方法是在初始化之后还是销毁之前调用

    3. 通过实现 InitializingBean/DisposableBean 接口来定制初始化之后/销毁之前的操作方法

    初始化

    package com.*.*.service;
    
    import org.springframework.beans.factory.InitializingBean;
    
    import javax.annotation.PostConstruct;
    
    /**
     * @author dhm
     * @desc
     * @date 2017/11/27
     */
    
    public class TestService implements InitializingBean {
        public TestService(){
            System.out.println("构造方法");
        }
    
    
        @Override
        public void afterPropertiesSet() throws Exception {
            System.out.println("重写InitializingBean的afterPropertiesSet()方法");
        }
    
        public void initMethod(){
            System.out.println("initMethod方法");
        }
    
        @PostConstruct
        public void initByPostConstruct(){
            System.out.println("PostConstruct初始化方法");
        }
    }
    <bean class="com.*.*.service.TestService" init-method="initMethod"/>

    测试结果 :

    构造方法
    PostConstruct初始化方法
    重写InitializingBean的afterPropertiesSet()方法
    initMethod方法方法

    销毁

    package com.*.*.service;
    
    import org.springframework.beans.factory.DisposableBean;
    
    import javax.annotation.PreDestroy;
    
    /**
     * @author dhm
     * @desc
     * @date 2017/11/27
     */
    
    public class TestService implements DisposableBean {
        public void destroyMethod(){
            System.out.println("destroyMethod方法");
        }
    
        @PreDestroy
        public void destroyByPreDestroy(){
            System.out.println("PreDestroy销毁前方法");
        }
    
        @Override
        public void destroy() throws Exception {
            System.out.println("重写DisposableBean的destroy方法");
        }
    }
    <bean class="com.*.*.service.TestService" destroy-method="destroyMethod"/>

    测试结果:

    PreDestroy销毁前方法
    重写DisposableBean的destroy方法
    destroyMethod方法

  • 相关阅读:
    char 转string
    博客,记忆的图谱。
    history
    openstack Icehouse发布
    数据库常用命令
    nagios
    screen
    openstack 流量控制
    sublime 3
    磁盘类型
  • 原文地址:https://www.cnblogs.com/duanhm234/p/7921533.html
Copyright © 2011-2022 走看看