1. 程式人生 > >Spring bean初始化與銷毀的幾種方式和區別

Spring bean初始化與銷毀的幾種方式和區別

pack ack 構造 rop struct service() throws esc println

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

Spring bean初始化與銷毀的幾種方式和區別