生命周期-@Bean指定初始化和销毁方法

通过在@Bean注解中添加 initMethod和destroyMethod来指定bean的初始化和销毁方法

@Configuration
public class MainConfigOfLifeCycle {

    @Bean(initMethod = "init", destroyMethod = "destroy")
    public Car car() {
        return new Car();
    }
}
public class Car {

    public Car() {
        System.out.println("car construct ....");
    }

    public void init() {
        System.out.println("init method");
    }

    public void destroy() {
        System.out.println("destroy method");
    }
}
public class IOCTestLifCycle {
    private ApplicationContext getContext() {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
        System.out.println("容器创建完成");
        return context;
    }

    @Test
    public void test01() {
        AnnotationConfigApplicationContext context = (AnnotationConfigApplicationContext) getContext();

        context.close();
    }
}
car construct ....
init method
容器创建完成
五月 24, 2019 2:52:56 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@161cd475: startup date [Fri May 24 14:52:56 CST 2019]; root of context hierarchy
destroy method

需要注意的是,多实例情况下,容器关闭时不会调用bean的销毁方法。

posted on 2019-05-24 14:57  星辰钟塔的玛利亚女士  阅读(176)  评论(0编辑  收藏  举报

导航