1.通過@Bean註解指定組件的初始化方法和銷燬方法
Bean的實現類:
public class Car {
private String name;
private int age;
public Car() {
System.out.println("構造器。。。。");
}
public void init(){
System.out.println("初始化方法");
}
public void destroy(){
System.out.println("銷燬方法");
}
}
通過@Bean註解指定組件的初始化方法和銷燬方法
@Scope("singleton")
@Bean(destroyMethod = "destroy",initMethod = "init")
public Car car(){
return new Car();
}
這裏必須強調的是在組件註冊時如果@Scop指定的是單實例bean,則容器會自動在關閉容器時調用該方法的銷燬方法,如果是多實例bean,則交給容器自己管理,容器關閉時也不會自動調用銷燬方法
*注 單實例 Bean使用的是餓漢式的單例模式,容器在創建時就初始化該Bean,多實例則是在調用時才初始化bean,且多實例bean每次都新創建一個bean對象
測試代碼:
public static void main(String[] args) {
AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(ApplicationConfig.class);
//容器創建完成分割線
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>");
Object car = context.getBean("car");
Object car2 = context.getBean("car");
System.out.println(car.equals(car2));
context.close();
}
單實例輸出:
多實例輸出:
2.通過繼承InitializingBean和DisposableBean接口實現
bean實現類代碼:(實現了單例模式)然後通過配置類註冊到IOC容器中
public class Tree implements InitializingBean, DisposableBean {
private Tree(){}
private static final Tree TREE =new Tree();
public static Tree getTree(){
return TREE;
}
@Override
public void destroy() throws Exception {
System.out.println("tree銷燬方法");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("tree afterPropertiesSet");
}
}
輸出:
3.通過JSR250中的註解實現
bean實現類:(通過Component註解添加到IOC中,掃描時@ComponentScan必須在配置類中)
@Component
public class Dog {
public Dog(){}
//構造器註解
@PostConstruct
public void init(){
System.out.println("dog init");
}
//銷燬方法
@PreDestroy
public void destroy(){
System.out.println("dog destroy");
}
測試輸出: