SpringBoot啟動(dòng)項(xiàng)目時(shí)實(shí)現(xiàn)加載緩存
在SpringBoot項(xiàng)目中,執(zhí)行啟動(dòng)時(shí)的初始化工作(如加載緩存)是一個(gè)常見的需求??梢酝ㄟ^多種方式實(shí)現(xiàn),包括使用@PostConstruct注解、實(shí)現(xiàn)ApplicationRunner或CommandLineRunner接口,以及監(jiān)聽Spring的生命周期事件。下面詳細(xì)介紹這些方法,并給出相應(yīng)的代碼示例。
方法一:使用 @PostConstruct 注解
@PostConstruct注解可以用來標(biāo)記一個(gè)方法,在依賴注入完成后立即執(zhí)行。
這個(gè)方法在Spring容器初始化完畢后自動(dòng)調(diào)用,非常適合做一些初始化工作。
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class CacheLoader {
@PostConstruct
public void loadCache() {
// 初始化緩存
System.out.println("Loading cache at startup...");
// 例如:緩存某些數(shù)據(jù)
}
}
方法二:實(shí)現(xiàn) CommandLineRunner 接口
實(shí)現(xiàn)CommandLineRunner接口的run方法,SpringBoot啟動(dòng)時(shí)會(huì)調(diào)用這個(gè)方法,適合用來執(zhí)行啟動(dòng)時(shí)的初始化任務(wù)。
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class CacheLoader implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// 初始化緩存
System.out.println("Loading cache at startup...");
// 例如:緩存某些數(shù)據(jù)
}
}
方法三:實(shí)現(xiàn) ApplicationRunner 接口
與CommandLineRunner類似,ApplicationRunner接口也是在SpringBoot啟動(dòng)完成后調(diào)用,但提供了更為豐富的ApplicationArguments對象,可以用于處理傳入的命令行參數(shù)。
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class CacheLoader implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
// 初始化緩存
System.out.println("Loading cache at startup...");
// 例如:緩存某些數(shù)據(jù)
}
}
方法四:監(jiān)聽 Spring 的生命周期事件
通過實(shí)現(xiàn)ApplicationListener接口或使用@EventListener注解,監(jiān)聽 ApplicationReadyEvent事件,在SpringBoot啟動(dòng)完成后執(zhí)行初始化工作。
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class CacheLoader implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
// 初始化緩存
System.out.println("Loading cache at startup...");
// 例如:緩存某些數(shù)據(jù)
}
}
或者使用 @EventListener 注解:
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class CacheLoader {
@EventListener(ApplicationReadyEvent.class)
public void onApplicationReady() {
// 初始化緩存
System.out.println("Loading cache at startup...");
// 例如:緩存某些數(shù)據(jù)
}
}
選擇合適的方法
選擇哪種方法取決于具體的需求和使用場景:
- 如果初始化工作是一個(gè)Bean的屬性,則推薦使用@PostConstruct注解。
- 如果需要訪問命令行參數(shù),推薦使用ApplicationRunner或CommandLineRunner。
- 如果需要監(jiān)聽?wèi)?yīng)用上下文事件,推薦使用ApplicationListener或 @EventListener。
示例:加載緩存數(shù)據(jù)
假設(shè)我們要在應(yīng)用啟動(dòng)時(shí)加載一些用戶數(shù)據(jù)到緩存中,以下是一個(gè)完整的示例:
示例代碼
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class CacheLoader implements CommandLineRunner {
private Map<Integer, String> userCache = new HashMap<>();
@Override
public void run(String... args) throws Exception {
// 模擬從數(shù)據(jù)庫加載用戶數(shù)據(jù)到緩存
userCache.put(1, "Alice");
userCache.put(2, "Bob");
userCache.put(3, "Charlie");
System.out.println("User cache loaded at startup: " + userCache);
}
public String getUserById(int userId) {
return userCache.get(userId);
}
}
測試類
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CacheLoaderApplication implements CommandLineRunner {
@Autowired
private CacheLoader cacheLoader;
public static void main(String[] args) {
SpringApplication.run(CacheLoaderApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
// 測試緩存數(shù)據(jù)
System.out.println("User with ID 1: " + cacheLoader.getUserById(1));
System.out.println("User with ID 2: " + cacheLoader.getUserById(2));
System.out.println("User with ID 3: " + cacheLoader.getUserById(3));
}
}
通過以上方式,可以確保在SpringBoot項(xiàng)目啟動(dòng)時(shí)執(zhí)行必要的初始化工作,如加載緩存數(shù)據(jù),從而提高應(yīng)用的性能和響應(yīng)速度。
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Springboot使用Spring Data JPA實(shí)現(xiàn)數(shù)據(jù)庫操作
Spring Data JPA 是 Spring 基于 Spring Data 框架、在JPA 規(guī)范的基礎(chǔ)上開發(fā)的一個(gè)框架,使用 Spring Data JPA 可以極大地簡化JPA 的寫法,本章我們將詳細(xì)介紹在Springboot中使用 Spring Data JPA 來實(shí)現(xiàn)對數(shù)據(jù)庫的操作2021-06-06
Java調(diào)用DeepSeek?api實(shí)現(xiàn)方法記錄
這篇文章主要介紹了如何在Java中調(diào)用DeepSeek?API,包括在官網(wǎng)獲取APIKeys、創(chuàng)建API請求工具類以及處理返回結(jié)果的步驟,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-02-02
Windows上安裝不同版本JDK并切換使用的詳細(xì)步驟
在Windows操作系統(tǒng)中,管理和切換Java Development Kit (JDK) 的版本是一項(xiàng)常見的任務(wù),尤其是在開發(fā)環(huán)境中,這篇文章主要介紹了Windows上安裝不同版本JDK并切換使用的相關(guān)資料,需要的朋友可以參考下2025-09-09
SpringBoot 使用WebSocket功能(實(shí)現(xiàn)步驟)
本文通過詳細(xì)步驟介紹了SpringBoot 使用WebSocket功能,首先需要導(dǎo)入WebSocket坐標(biāo),編寫WebSocket配置類,用于注冊WebSocket的Bean,結(jié)合示例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-02-02
MyBatis批量操作XML的完整實(shí)現(xiàn)方案
本文介紹了MyBatis通過XML映射文件實(shí)現(xiàn)批量插入、更新和刪除的完整方案,包括單條SQL批量插入、批量插入并返回主鍵、批量更新、批量刪除以及動(dòng)態(tài)批量操作,最后,分享了最佳實(shí)踐建議,需要的朋友可以參考下2025-12-12
springboot 如何通過SpringTemplateEngine渲染html
通過Spring的Thymeleaf模板引擎可以實(shí)現(xiàn)將模板渲染為HTML字符串,而不是直接輸出到瀏覽器,這樣可以對渲染后的字符串進(jìn)行其他操作,如保存到文件或進(jìn)一步處理,感興趣的朋友跟隨小編一起看看吧2024-10-10
使用Java WebSocket獲取客戶端IP地址的示例代碼
在開發(fā)Web應(yīng)用程序時(shí),我們通常需要獲取客戶端的 IP 地址用于日志記錄、身份驗(yàn)證、限制訪問等操作,本文將介紹如何使用Java WebSocket API獲取客戶端IP地址,以及如何在常見的WebSocket框架中獲得客戶端 IP地址,需要的朋友可以參考下2023-11-11
SpringBoot集成slf4j2日志配置的實(shí)現(xiàn)示例
本文主要介紹了SpringBoot集成slf4j2日志配置的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-08-08

