Bean的初始化和销毁的行为可以有三种自定义方式
1)实现Bean对应类的接口 InitializingBean,DisposableBean,重写方法;
2)在Spring.xml的配置中,指定它的初始化和销毁方法;
3)在Spring.xml的配置中,指定全局的针对所有bean的默认的初始化和销毁方法.
对于一个bean,仅当没有定义方式1和2的情况下,方式3才会生效。
当方式1和2都定义的情况下,先执行方式2的方法,然后才执行方式1定义的方法
spring.xml配置
<?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="defaultInit" default-destroy-method="defaultDestroy"><!-- 全局默认的初始化和销毁方法 -->
<!-- 指定的初始化和销毁方法 -->
<bean id="beanLifeCycle" class="com.imooc.lifecycle.BeanLifeCycle" init-method="start" destroy-method="stop">
<!-- 实现接口的初始化和销毁方法 -->
<!-- <bean id="beanLifeCycle" class="com.imooc.lifecycle.BeanLifeCycle"> -->
</bean>
</beans>
一个bean类
package com.imooc.lifecycle;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class BeanLifeCycle implements InitializingBean, DisposableBean {
//指定的初始化和销毁方法
public void start() {
System.out.println("1 Bean start.");
}
public void stop() {
System.out.println("1 Bean stop.");
}
//实现接口的初始化和销毁方法
public void destroy() throws Exception {
System.out.println("2 Bean destroy.");
}
public void afterPropertiesSet() throws Exception {
System.out.println("2 Bean afterPropertiesSet.");
}
//全局默认的初始化和销毁方法
public void defaultInit() {
System.out.println("3 Bean defaultInit.");
}
public void defaultDestroy() {
System.out.println("3 Bean defaultDestroy.");
}
}