学习记录

来源:互联网 发布:什么是数据流程分析 编辑:程序博客网 时间:2024/06/08 07:40
1.配置单个Bean的初始化和销毁方法
        <bean id="beanLifeCycle" class="com.imooc.lifecycle.BeanLifeCycle"  init-method="start" destroy-method="stop"></bean>

指定的类中必须有start()和stop()方法。

public void start() {System.out.println("Bean start .");}public void stop() {System.out.println("Bean stop.");}

2.配置全局默认初始化,销毁方法

<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="defautInit" default-destroy-method="defaultDestroy">


全部的类中的默认初始化和销毁方法

public void defautInit() {System.out.println("Bean defautInit.");}public void defaultDestroy() {System.out.println("Bean defaultDestroy.");}


3.初始化和销毁的另外一种实现方式

初始化:实现InitializingBean接口,覆盖afterPropertiesSet()方法

@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("Bean afterPropertiesSet.");}

销毁:实现DisposableBean接口,覆盖destroy()方法

@Overridepublic void destroy() throws Exception {System.out.println("Bean destroy.");}

4. 三种方法都使用的时候的顺序


默认的初始化和销毁方法被单独Bean配置方法覆盖,接口方法初始化比Bean单独配置方法早。

PS.1.只要配置了默认的初始化,销毁方法,即使类中没有对应的默认初始化和销毁方法,Bean的初始化过程也不会失败。

       2.单独配置Bean初始化和销毁方法,如果没有方法,会报错。

0 0