簡體   English   中英

在應用程序啟動期間從數據庫加載數據

[英]Loading data from database during application startup

DB(Oracle) 中有一個表,用於存儲“代碼”及其“描述”。 我需要在應用程序啟動期間加載此表數據並將其存儲在變量(可能是 Map 對象)中,以便我可以查找每個請求的代碼描述,而無需為每個請求訪問數據庫。 什么是最好的方法來做到這一點?

Application 是一個基於 Spring 框架的獨立 Java 應用程序。

謝謝。

我不確定,但 Spring 事件可能會有所幫助。 例如,您可以使用 ContextRefreshedEvent - 每當 Spring Context 啟動或刷新時都會發布此事件。

請檢查: running-code-on-spring-boot-startupbetter-application-events-in-spring-framework-4-2

您可以創建一個選擇應用程序啟動方法的類。 在 spring 中,您可以使用ApplicationReadyEvent事件實現ApplicationListener接口。

此時,您的應用程序已准備好與數據庫通信並將自動執行您的代碼。

@Component
public class AppBootstrapListener implements ApplicationListener<ApplicationReadyEvent> {

    //Inject Service or repository if you have.

    /**
    * Executes on application ready event
    * Check's if data exists & calls to create or read data
    */
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // code here
    }

}

對於任何澄清添加評論

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM