Spring Boot使用JSR250標準的@PostConstruct和@PreDestroy註解定製Bean的生命週期

在前面的博客中,我們使用了Spring自定義的兩種方式(設置@Bean參數和實現接口)來定製Bean的生命週期。這篇博客將介紹如何使用JSR250標準定義的@PostConstrut和@PreDestroy註解來定製Bean的生命週期。

  • 創建Bean的類,並且註解對應的方法:
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class Module {
    public Module(){
        System.out.println("The Module Bean is being created.");
    }

    //The PostConstruct annotation is used on a method that needs to be executed
    //after dependency injection is done to perform any initialization.
    @PostConstruct
    public void postConstruct(){
        System.out.println("The postConstruct method is calling.");
    }

    //The PreDestroy annotation is used on methods as a callback notification to signal
    // that the instance is in the process of being removed by the container.
    @PreDestroy
    public void preDestroy(){
        System.out.println("The preDestroy method is calling.");
    }
}
  • 代碼上的英文註釋爲源碼的註釋,這裏簡單翻譯一下:
  1. @PostConstrut:PostConstruct 爲方法註解,被註解的方法在依賴注入後結束後執行。
  2. @PreDestroy:PreDestroy註解爲方法註解,作爲一個當實例被移出容器的回調信號(簡單理解爲在Bean被移出容器後調用被註解的方法)。
  3. 這裏爲了更好的演示,在構造器中打印了一句話。
  • 通過使用配置類和@Bean註解把Module實例注入容器:
import com.michael.annotation.demo.POJO.Module;
import org.springframework.context.annotation.*;

@Configuration
public class MyConfig {

    @Bean("Module1")
    @Scope("singleton")
    public Module module(){
        return new Module();
    }
}
  • 測試代碼:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

import static java.lang.System.out;
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        ApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
        out.println("The container has been initialized.");
         for(String name : applicationContext.getBeanDefinitionNames()){
             if(!name.contains("."))
                out.println(name);
        }
        out.println("The container has been destroyed.");
    }
}
  • 輸出:
The Module Bean is being created.
The postConstruct method is calling.
2020-03-25 15:20:23.615  INFO 28087 --- [           main] c.m.annotation.demo.DemoApplication      : Started DemoApplication in 0.652 seconds (JVM running for 0.968)
The container has been initialized.
demoApplication
test
myConfig
personService
Module1
propertySourcesPlaceholderConfigurer
taskExecutorBuilder
applicationTaskExecutor
taskSchedulerBuilder
The container has been destroyed.
The preDestroy method is calling.
  • 這裏可以看出,postConstruct方法是在Module類的構造器調用結束後被執行的。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章