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方法

  • 相关阅读:
    Vasya and Endless Credits CodeForces
    Dreamoon and Strings CodeForces
    Online Meeting CodeForces
    数塔取数 基础dp
    1001 数组中和等于K的数对 1090 3个数和为0
    1091 线段的重叠
    51nod 最小周长
    走格子 51nod
    1289 大鱼吃小鱼
    POJ 1979 Red and Black
  • 原文地址:https://www.cnblogs.com/duanhm234/p/7921533.html
Copyright © 2011-2022 走看看