一、@Bean注解指定初始化和销毁方法
- 创建BeanTest类,自定义初始化方法和销毁方法。
- 在@Bean注解的参数中指定BeanTest自定义的初始化和销毁方法:
- 销毁方法只有在IOC容器关闭的时候才调用。
代码如下:
public class BeanTest {
public BeanTest(){
System.out.println("BeanTest被创建");
}
public void init(){
System.out.println("BeanTest被初始化");
}
public void destory(){
System.out.println("BeanTest被销毁");
}
}
/**
* @Version: 1.0.0
* @Author: Dragon_王
* @ClassName: MyConfig
* @Description: TODO描述
* @Date: 2024/1/21 22:59
*/
@Configuration
@ComponentScan(("com.dragon.restart1"))
public class MyConfig {
@Bean(initMethod = "init",destroyMethod = "destory")
public BeanTest beanTest(){
return new BeanTest();
}
}
//测试代码
AnnotationConfigApplicationContext ct = new AnnotationConfigApplicationContext(MyConfig.class);
System.out.println("IoC容器创建完成");
- 可以看到调用的是自定义的方法,这里解释一下,测试时,运行完代码块程序就结束了,所哟IoC容器就被关闭,所以调用了IoC销毁方法。同时可以看到初始化方法在对象创建完成后调用。
- 当组件的作用域为单例时在容器启动时即创建对象,而当作用域为原型(PROTOTYPE)时在每次获取对象的时候才创建对象。并且当作用域为原型(PROTOTYPE)时,IOC容器只负责创建Bean但不会管理Bean,所以IOC容器不会调用销毁方法。
二、实现InitializingBean接口和DisposableBean接口
看一下两接口的方法:
public interface InitializingBean {
/**
* Invoked by the containing {@code BeanFactory} after it has set all bean properties
* and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.
* <p>This method allows the bean instance to perform validation of its overall
* configuration and final initialization when all bean properties have been set