Spring Boot 中Bean的初始化后和銷毀前的處理


Spring 對Bean的生命周期的操作提供了支持。具體實現又兩種方式

1.使用@Bean 中的 initMethod 和 destroyMethod
2.注解方式 利用JSR-250 中的@PostConstruct 和 @PreDesctroy


兩種方式的具體用法如下

1.創建功能,為了快速完成項目構建,我們使用 https://start.spring.io/ 網址來快速生成項目

 

 

 

2.引入Jsr250 支持
    

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

 

3.使用@Bean 的形式

    

package com.lvlvstart.example.service;

public class BeanWayService {

    public void init(){
        System.out.println("@Bean-init-method - BeanWayService");
    }

    public BeanWayService(){
        super();
        System.out.println("Init constructor method - BeanWayService");
   }

    public void destroy(){
        System.out.println("@Bean-destory-method - BeanWayService");
    }

}

  

4.使用Jsr250的形式

    

package com.lvlvstart.example.service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class Jsr250Service {

  @PostConstruct
  public void init(){
  System.out.println("@Bean-init-method-Jsr250Service");
  }

  public Jsr250Service(){
    super();
    System.out.println("Init constructor method - Jsr250Service");
  }

  @PreDestroy
  public void destroy(){
    System.out.println("@Bean-destory-method-Jsr250Service");
  }

 


}

 

5.配置類

    

package com.lvlvstart.example.config;

import com.lvlvstart.example.service.BeanWayService;
import com.lvlvstart.example.service.Jsr250Service;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.lvlvstart.example")
public class Config {

  @Bean(initMethod = "init" , destroyMethod = "destroy")
  BeanWayService beanWayService(){
    return new BeanWayService();
  }

  @Bean
  Jsr250Service jsr250Service(){
    return new Jsr250Service();
  }

}

 

6.啟動類

    

package com.lvlvstart.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ExampleApplication {

  public static void main(String[] args) {
    SpringApplication.run(ExampleApplication.class, args);
  }

}

 

     

參考資料: 《Spring Boot 實戰 》 王雲飛 著


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM