Bean的生命周期 : 创建bean对象 – 属性赋值 – 初始化方法调用前的操作 – 初始化方法 – 初始化方法调用后的操作 – …-- 销毁前操作 – 销毁方法的调用。
【1】init-method和destroy-method
自定义初始化方法和销毁方法两种方式:xml配置和注解。
① xml配置
<bean id="person"
class="com.core.Person" scope="singleton"
init-method="init" destroy-method="cleanUp"
autowire="byName" lazy-init="true" >
</bean>
② 注解配置
@Scope("singleton")
@Lazy
@Bean(name="person",initMethod="init",destroyMethod="cleanUp",
autowire=Autowire.BY_NAME)
public Person person01(){
return new Person("lisi", 20);
}
单实例bean在容器创建完成前会进行创建并初始化,在容器销毁的时候进行销毁。多实例bean(scope=prototype)在第一次获取该bean实例时才会创建并初始化,且容器不负责该bean的销毁。
【2】InitializingBean 和DisposableBean
InitializingBean 接口:
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
-
在BeanFactory设置完bean属性后执行
-
需要被bean实现的接口,一旦bean的属性被BeanFactory设置后需要做出反应: 如,执行自定义初始化,或者仅仅是检查是否设置了所有强制属性。
-
实现InitializingBean 的可替代方式为给bean指定一个自定义的init-method,例如在一个xml bean 定义中。
-
在bean的属性设置之后进行操作,不返回任何值但是允许抛出异常。
DisposableBean接口:
public interface DisposableBean {
void destroy() throws Exception;
}
- 被bean实现的接口,在销毁时释放资源,在Bean销毁的时候调用该方法。
- 如果销毁一个缓存的单例,一个BeanFactory 可能会调用这个销毁方法。
- 在容器关闭时,应用上下文会销毁所有的单例bean。
- 一种替代实现DisposableBean 接口的方案为指定一个自定义的destroy-method方法,例如在一个xml bean定义中。
自定义bean实现上述两个接口
@Component
public class Cat implements InitializingBean,DisposableBean {
public Cat(){
System.out.println("cat constructor...");
}
@Override
public void destroy() throws Exception {
// TODO Auto-generated method stub
System.out.println("cat...destroy...");
}
@Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
System.out.println("cat...afterPropertiesSet...");
}
}
测试结果
cat constructor...
cat...afterPropertiesSet...
容器创建完成...
四月 08, 2018 6:35:46 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext
doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@11028347:
startup date [Sun Apr 08 18:35:46 CST 2018]; root of context hierarchy
cat...destroy...
【3】@PostConstruct和@PreDestroy
使用JSR250规范定义的两个注解:
- @PostConstruct: PostConstruct注解作用在方法上,在依赖注入完成后进行一些初始化操作。这个方法在类被放入service之前被调用,所有支持依赖项注入的类都必须支持此注解。
- @PreDestroy:在容器销毁bean之前通知我们进行清理工作
【4】BeanPostProcessor-Bean后置处理器
① 什么是bean后置处理器
在bean初始化前后进行一些处理工作
- postProcessBeforeInitialization:在初始化之前工作
- postProcessAfterInitialization:在初始化之后工作
【5】Spring底层使用BeanPostProcessor