1. 程式人生 > >最佳實踐--Spring容器初始化完成之後執行某個方法

最佳實踐--Spring容器初始化完成之後執行某個方法

在做javaweb專案的時候,當用戶訪問的時候需要從資料庫載入資料,現在要在容器初始化完成之後直接把資料放入快取,當用戶訪問的時候提高速度。

查閱相關spring文件,找到了一個最佳實踐(best practice)

The JSR-250 @PostConstruct and @PreDestroy annotations are generally considered best practice for receiving lifecycle callbacks in a modern Spring application. Using these annotations means that your beans are not coupled to Spring specific interfaces. For details see Section 6.9.8, “@PostConstruct and @PreDestroy”.
If you don’t want to use the JSR-250 annotations but you are still looking to remove coupling consider the use of init-method and destroy-method object definition metadata.

詳情看參考文獻

直接上程式碼

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Component;
@Component
public class InitData {
    @PostConstruct
    public void init() {
        System.out.println("初始化資料方法");
    }
}

這裡寫圖片描述

參考文獻