• 生命周期-@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的销毁方法。

  • 相关阅读:
    剑指offer_11:二进制中1的个数
    剑指offer_10:矩形覆盖
    spring mvc 访问静态资源
    spring context:component-scan ex
    spring aop配置未生效
    415 Unsupported Media Type
    spring mvc 接收List对象入参
    JIRA甘特图
    JIRA的工时
    JIRA导出工作日志到Excel
  • 原文地址:https://www.cnblogs.com/AyasatoMayoi/p/10918207.html
Copyright © 2020-2023  润新知