省時(shí)又高效!Spring Boot 內(nèi)置這十個(gè)功能,99% 開發(fā)者都在用
在構(gòu)建基于 Spring Boot 的服務(wù)時(shí),我們并不需要從零開始造輪子。Spring Boot 已經(jīng)在底層集成了一系列高效的特性,覆蓋日志、配置、依賴管理、請(qǐng)求處理、任務(wù)調(diào)度、監(jiān)控等關(guān)鍵環(huán)節(jié)。以下將從工程實(shí)用角度出發(fā),系統(tǒng)梳理這些內(nèi)置能力,助你開發(fā)效率倍增、系統(tǒng)更穩(wěn)定。
1、全流程請(qǐng)求日志追蹤 CommonsRequestLoggingFilter
請(qǐng)求過程中的參數(shù)、IP、Header、Payload 等調(diào)試信息,在系統(tǒng)排查問題時(shí)至關(guān)重要。CommonsRequestLoggingFilter 就是 Spring Boot 提供的一個(gè)簡潔工具,用于收集這類數(shù)據(jù)。
@Configuration
public class RequestLoggingConfig {
@Bean
public CommonsRequestLoggingFilter logFilter() {
CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter();
filter.setIncludeQueryString(true);
filter.setIncludePayload(true);
filter.setMaxPayloadLength(1024);
filter.setAfterMessagePrefix("[REQUEST DATA] ");
return filter;
}
}
配置啟用 DEBUG 級(jí)別日志:
logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG
2、請(qǐng)求體/響應(yīng)體可重復(fù)讀取
ContentCachingRequestWrapper 和 ContentCachingResponseWrapper 能解決 Servlet 流只能讀取一次的問題,非常適合在請(qǐng)求體寫入業(yè)務(wù)前就進(jìn)行日志記錄或內(nèi)容修改。
// 請(qǐng)求體緩存
@Component
public class RequestLogFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
ContentCachingRequestWrapper wrapped = new ContentCachingRequestWrapper(req);
log.debug("Payload: {}", new String(wrapped.getContentAsByteArray()));
chain.doFilter(wrapped, res);
}
}
// 響應(yīng)簽名處理
@Component
public class ResponseSignFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
ContentCachingResponseWrapper wrapped = new ContentCachingResponseWrapper(res);
chain.doFilter(req, wrapped);
String sign = Base64.getEncoder().encodeToString(wrapped.getContentAsByteArray());
wrapped.setHeader("X-Response-Signature", sign);
wrapped.copyBodyToResponse();
}
}
3、防止過濾器重復(fù)執(zhí)行 OncePerRequestFilter 基類
Spring 提供的 OncePerRequestFilter 可確保每次 HTTP 請(qǐng)求生命周期中,僅執(zhí)行一次過濾邏輯,解決多次 forward/include 造成的重復(fù)問題。
適用于:日志埋點(diǎn)、安全校驗(yàn)、性能計(jì)量等。
4、AOP 三大工具類
Spring AOP 提供的輔助類如下:
- AopContext.currentProxy():拿到當(dāng)前代理對(duì)象,解決同類方法間調(diào)用注解失效的問題。
- AopUtils.isXxxProxy():識(shí)別當(dāng)前代理是 JDK 還是 CGLIB。
- ReflectionUtils:方便執(zhí)行私有字段/方法反射訪問。
Field field = ReflectionUtils.findField(SomeClass.class, "secret");
ReflectionUtils.makeAccessible(field);
Object value = ReflectionUtils.getField(field, instance);
5、Starter 架構(gòu)統(tǒng)一依賴配置
Spring Boot 的 Starter 模塊通過一組命名規(guī)范將核心依賴打包,開發(fā)者僅需引入 spring-boot-starter-* 即可自動(dòng)獲取所需組件。
示例:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
想構(gòu)建自定義 Starter?
- 添加 META-INF/spring.factories。
- 編寫 @Configuration 配置類配合 @ConditionalOnXxx 注解進(jìn)行智能裝配。
6、自動(dòng)配置與配置綁定
通過 @ConfigurationProperties 和 ${} 占位符,Spring Boot 可以靈活地從配置文件中讀取類型安全的屬性,告別硬編碼:
@Configuration
@ConfigurationProperties(prefix = "app")
public class AppConfig {
private String env;
private DatabaseConfig database;
public static class DatabaseConfig {
private String url;
private String username;
}
}
app:
env: prod
database:
url: jdbc:mysql://localhost:3306/test
username: root
7、簡單上手的異步與定時(shí)執(zhí)行
- @Async 配合線程池,輕松實(shí)現(xiàn)異步調(diào)用。
- @Scheduled 用于配置定時(shí)任務(wù)(固定速率、Cron 表達(dá)式等)。
@Async("customExecutor")
public CompletableFuture<Void> handleTask(String id) {
return CompletableFuture.runAsync(() -> {
// 長耗時(shí)邏輯
});
}
@Scheduled(cron = "0 0 1 * * ?")
public void clearLogs() {
// 每日凌晨清理任務(wù)
}
8、內(nèi)建運(yùn)維支持:Spring Boot Actuator
通過 /actuator/* 端點(diǎn),開發(fā)者可實(shí)時(shí)觀察應(yīng)用運(yùn)行狀況,并通過 MeterRegistry 自定義指標(biāo):
@Async("customExecutor")
public CompletableFuture<Void> handleTask(String id) {
return CompletableFuture.runAsync(() -> {
// 長耗時(shí)邏輯
});
}
@Scheduled(cron = "0 0 1 * * ?")
public void clearLogs() {
// 每日凌晨清理任務(wù)
}
9、SpEL 表達(dá)式語言
Spring 表達(dá)式語言(SpEL)用于動(dòng)態(tài)計(jì)算,支持條件注解、配置注入、安全控制等多種場(chǎng)景:
@Autowired
private MeterRegistry meterRegistry;
public void countEvent(String type) {
meterRegistry.counter("event.count", "type", type).increment();
}
10、配置驅(qū)動(dòng)開發(fā)理念
Spring Boot 倡導(dǎo)配置即代碼,優(yōu)雅實(shí)現(xiàn)按需加載、環(huán)境隔離、屬性映射,覆蓋數(shù)據(jù)庫、消息、緩存、HTTP 等全棧組件。只需關(guān)注業(yè)務(wù)核心邏輯,底層交由框架處理。
結(jié)語
Spring Boot 為開發(fā)者預(yù)置了大量高效機(jī)制,不需要外部集成,也無需復(fù)雜配置。善用這些內(nèi)建能力,將極大提升你的開發(fā)節(jié)奏、項(xiàng)目質(zhì)量與系統(tǒng)彈性。在企業(yè)級(jí)應(yīng)用中,這些功能已被廣泛應(yīng)用于微服務(wù)、網(wǎng)關(guān)、后臺(tái)管理系統(tǒng)等場(chǎng)景中,建議靈活組合使用。