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

  • 相关阅读:
    eclipse取消validation验证
    VMware12 pro装unlocker207补丁后依然没有apple mac选项,问题解决
    OSG学习:使用OSG中预定义的几何体
    技嘉主板+AMD CPU开启CPU虚拟化方法
    OSG学习:用多通道(multiple passes)实现透明度
    shader language学习(1)——shader language简介背景
    OSG学习:阴影代码示例
    代码整洁之道_条件判断
    springboot使用hibernate validator校验
    解决spring boot在RabbitMQ堆积消息情况下无法启动问题
  • 原文地址:https://www.cnblogs.com/duanhm234/p/7921533.html
Copyright © 2011-2022 走看看