Bean的生命周期(3种方式)

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");
    }

测试输出:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章