生命周期 02 实现InitializingBean, DisposableBean接口
Cat.java
package com.example.annotations.bean;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
/**
* 生命周期测试
*/
public class Cat implements InitializingBean, DisposableBean {
/**
* 构造
*/
public Cat() {
System.out.println("cat constructor ...");
}
/**
* 做初始化方法
* 初始化方法不可以有参数 但可以抛异常
*/
public void init() {
System.out.println("cat init ...");
}
/**
* 初始化设置完属性后
* 来源于 InitializingBean
* @throws Exception
*/
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("cat afterPropertiesSet ...");
}
/**
* 销毁的时候调用
* 来源于 DisposableBean
* @throws Exception
*/
@Override
public void destroy() throws Exception {
System.out.println("cat destroy ...");
}
public void destroyMethod() {
System.out.println("cat destroyMethod ...");
}
}
MainConfigOfLifeCycle.class中添加以下方法
@Bean(value = "cat4LifeCycle",initMethod = "init",destroyMethod = "destroyMethod")
public Cat cat(){
return new Cat();
}
测试
@Test
void lifeCycleTest(){
//配置类测试
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
System.out.println("容器创建完毕");
//获取bean
System.out.println("准备获取bean");
Object car4LifeCycle = applicationContext.getBean("cat4LifeCycle");
System.out.println("获取完毕");
//关闭容器
applicationContext.close();
System.out.println("容器已关闭");
}
运行结果: