1. 程式人生 > >學習 Spring (四) Bean 的生命周期

學習 Spring (四) Bean 的生命周期

exce utf-8 schema 實現 row tar ring () 全局

Spring入門篇 學習筆記

定義 --> 初始化 --> 使用 --> 銷毀

初始化

  1. 實現 org.springframework.beans.factory.InitializingBean 接口,覆蓋 afterPropertiesSet 方法

    public class ExampleBean implements InitializingBean{
        public void afterPropertiesSet() throws Exception{
        // do some initialization work
        }
    
    }
  2. 配置 init-method:

    <bean id="exampleInitBean" class="example.ExampleBean" init-method="start"/>
    public class ExampleBean{
        public void start(){
        // do some initialization work
        }
    
    }

銷毀

  1. 實現 org.springframework.beans.factory.DisposableBean 接口,覆蓋 destory 方法

    public class ExampleBean implements DisposableBean{
        public void destory() throws Exception{
        // do some destruction work
        }
    
    }
  2. 配置 destory-method

    <bean id="exampleInitBean" class="example.ExampleBean" destory-method="stop"/>
    public class ExampleBean{
        public void stop(){
        // do some destruction work
        }
    
    }

配置全局默認初始化、銷毀方法

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd" 
        default-init-method="init" default-destory-method="destory">
    
 </beans>

多種方式同時使用執行順序

  1. afterPropertiesSet()
  2. init-method / default-init-method
  3. destory()
  4. destory-method / default-destory-method
  • 如果同時配置了 init-method 和 default-init-method 或 destory-method 和 default-destory-method,default-init-method 或 default-destory-method 不執行
  • default-init-method 和 default-destory-method 可以不在 Bean 中聲明

源碼:learning-spring

學習 Spring (四) Bean 的生命周期