打卡2:Bean的初始化和銷燬

一. Bean初始化和銷燬的方式

  1. Java配置方式
    使用@Bean的initMethod和destroyMethod(等同於xml配置的init-method和destroy-method)

  2. 註解方式
    使用JSR-250的@PostConstr和PreDestroy
    注:此方式需增加JSR250支持

     <dependency>
                <groupId>javax.annotation</groupId>
                <artifactId>jsr250-api</artifactId>
                <version>1.0</version>
     </dependency>
    

二. 示例解析

  1. @Bean形式的Bean

    public class BeanWayService {
        public void init() {
            System.out.println("@Bean-init-method");
        }
    
        public BeanWayService() {
            super();
            System.out.println("初始化構造函數-BeanWayService");
        }
    
        public void destory() {
            System.out.println("@Bean-destory-method");
        }
    }
    
  2. JSR250形式的Bean

    public class JSR250WayService {
    
        @PostConstruct //在構造函數執行完之後執行
        public void init() {
            System.out.println("jsr250-init-method");
        }
    
        public JSR250WayService() {
            super();
            System.out.println("初始化構造函數-JSR250WayService");
        }
    
        @PreDestroy //在Bean銷燬之前執行
        public void destory() {
            System.out.println("jsr250-destory-method");
        }
    }
    
  3. 配置類

    @Configuration
    @ComponentScan("com.muzi.springboot01.chapter2.prepost")
    public class PrePostConfig {
    
        @Bean(initMethod = "init", destroyMethod = "destory") //指定init()和destroy()在構造函數之後、Bean銷燬前執行
        BeanWayService beanWayService() {
            return new BeanWayService();
        }
    
        @Bean
        JSR250WayService jsr250WayService() {
            return new JSR250WayService();
        }
    }
    
  4. 運行

    public class Main {
    
        public static void main(String[] args) {
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PrePostConfig.class);
            BeanWayService beanWayService = context.getBean(BeanWayService.class);
            JSR250WayService jsr250WayService = context.getBean(JSR250WayService.class);
    
            context.close();
        }
    }
    
  5. 運行結果
    在這裏插入圖片描述

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