通过实现 InitializingBean 和 DisposableBean 接口,也可以指定 bean 的初始化和销毁方法
二、Student 类
public class Student implements InitializingBean,DisposableBean{ public Student(){
System.out.println("创建 Student 对象");
} //销毁方法
public void destroy() throws Exception {
System.out.println("销毁对象");
} //初始化方法
public void afterPropertiesSet() throws Exception {
System.out.println("初始化");
}}
二、配置类
@Configuration
public class ConfigOfLifeCycle { @Bean
public Student student(){
return new Student();
}
}
三、测试类
@Test
@SuppressWarnings("resource")
public void test3(){
//创建 ioc 容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ConfigOfLifeCycle.class); //关闭容器:用来测试 destory() 方法
applicationContext.close();
}