zoukankan      html  css  js  c++  java
  • 注解-生命周期01-指定初始化/销毁方法

    一、@Bean指定初始化和销毁方法

    public class Car {
        public Car() {
            System.out.println("Car Constructor...");
        }
        public void init(){
            System.out.println("Car...init...");
        }
        public void destory(){
            System.out.println("Car...destroy...");
        }
    }
    Car
    @ComponentScan("spring.com.life")
    @Configuration
    public class MainConfigOfLifeCycle {
        @Bean(initMethod = "init",destroyMethod = "destory")
        public Car car(){
            return new Car();
       }
    }

    二、实现InitializingBean、DisposableBean接口

    @Component
    public class Cat implements InitializingBean, DisposableBean {
        public Cat() {
            System.out.println("Cat Constructor...");
        }
    
        @Override
        public void destroy() throws Exception {
            System.out.println("Cat...destroy...");
        }
    
        @Override
        public void afterPropertiesSet() throws Exception {
            System.out.println("Cat...init...");
        }
    }

    三、@PostConstruct、@PreDestroy

      @PostConstruct: 在bean创建完成并且属性赋值完成,来执行初始化方法。

      @PreDestroy:在容器销毁bean之前通知我们进行清理工作。

    @Component
    public class Dog {
        public Dog() {
            System.out.println("Dog Constructor...");
        }
        @PostConstruct
        public void init(){
            System.out.println("Dog...PostConstruct...");
        }
        @PreDestroy
        public void destory(){
            System.out.println("Dog...PreDestroy...");
        }
    }
  • 相关阅读:
    app启动优化
    CountDownLatch妙用
    匿名内部类为什么有可能造成内存泄漏
    单例模式为什么有可能造成内存泄漏
    左移右移记不住怎么办
    说一说ThreadLocal
    对framework层的一些看法
    双重锁单例
    JMM总结
    关于lock前缀
  • 原文地址:https://www.cnblogs.com/qmillet/p/13085397.html
Copyright © 2011-2022 走看看