SpringBoot自動(dòng)裝配注解的實(shí)現(xiàn)示例
這份指南詳細(xì)整理了 Spring Boot 中最核心的配置綁定、自動(dòng)裝配以及條件注解。這些注解是理解 Spring Boot "約定大于配置" (Convention over Configuration) 機(jī)制的基石。
本文檔詳細(xì)解析 Spring Boot 中用于配置綁定、自動(dòng)裝配流程控制及條件加載的核心注解。
1. 配置屬性綁定 (Configuration Binding)
這一組注解的主要作用是將 application.yml 或 application.properties 中的配置值綁定到 Java Bean 中。
@ConfigurationProperties
- 用途:將配置文件中指定前綴的屬性值自動(dòng)綁定到 Java 類的字段上。
- 關(guān)鍵點(diǎn):
- 僅僅加上這個(gè)注解,Spring 容器并不會(huì)自動(dòng)注冊它。它需要配合 @EnableConfigurationProperties 或 @Component (配合掃描) 使用。
- 支持松散綁定 (Relaxed Binding),例如 first-name 可以綁定到 firstName。
@EnableConfigurationProperties
- 用途:顯式地開啟 @ConfigurationProperties 注解類的功能,并將該類注冊為 Spring Bean。
- 場景:通常用在 @Configuration 類上,用于引入第三方的配置類,或者當(dāng)你不想在配置類上加 @Component 時(shí)使用。
@ConfigurationPropertiesScan
- 用途:從 Spring Boot 2.2 開始引入。它會(huì)掃描指定包路徑下所有標(biāo)注了 @ConfigurationProperties 的類,并自動(dòng)注冊為 Bean。
- 優(yōu)勢:省去了在配置類上寫一堆 @EnableConfigurationProperties({A.class, B.class}) 的麻煩。
?? 代碼示例
1. 配置文件 (application.yml)
app:
server:
timeout: 5000
enabled: true2. 配置類 POJO
import org.springframework.boot.context.properties.ConfigurationProperties;
// 聲明前綴,Spring 會(huì)去查找 app.server.*
@ConfigurationProperties(prefix = "app.server")
public class ServerProperties {
private Integer timeout;
private boolean enabled;
// 必須要有 Getter/Setter
public Integer getTimeout() { return timeout; }
public void setTimeout(Integer timeout) { this.timeout = timeout; }
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
}3. 啟用配置 (三種方式選其一)
方式 A:配合 @Component (最簡單)
- 在
ServerProperties上直接加@Component,配合@ConfigurationProperties。
- 在
方式 B:使用 @EnableConfigurationProperties (推薦用于庫開發(fā))
@Configuration @EnableConfigurationProperties(ServerProperties.class) public class MyConfig { ... }方式 C:使用 @ConfigurationPropertiesScan (適合大型項(xiàng)目)
@SpringBootApplication @ConfigurationPropertiesScan("com.example.config") // 掃描指定包 public class MyApplication { ... }
2. 自動(dòng)裝配核心 (Auto Configuration)
@EnableAutoConfiguration
用途:Spring Boot 的魔法核心。它告訴 Spring Boot 根據(jù)添加的 jar 依賴自動(dòng)配置 Spring 應(yīng)用。
原理:
- 它利用 SpringFactoriesLoader 機(jī)制。
- 掃描 classpath 下所有 jar 包中的 META-INF/spring.factories (Spring Boot 2.x) 或 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports (Spring Boot 3.x)。
- 加載其中聲明的配置類,但在加載前會(huì)通過 @Conditional 系列注解進(jìn)行過濾。
注意:通常包含在 @SpringBootApplication 中,很少單獨(dú)使用。
3. 條件注解 (Conditionals)
這一組注解決定了 Bean 是否會(huì)被創(chuàng)建并注冊到容器中。這是實(shí)現(xiàn)“自動(dòng)裝配”邏輯判斷的關(guān)鍵。
@Conditional
- 用途:最底層的注解。它接收一個(gè)實(shí)現(xiàn)了 Condition 接口的類。只有當(dāng) matches 方法返回 true 時(shí),Bean 才會(huì)被創(chuàng)建。
- 場景:編寫非常復(fù)雜的自定義邏輯判斷時(shí)使用。
@ConditionalOnProperty
用途:這是 @Conditional 的擴(kuò)展,專門用于判斷配置文件中是否存在某個(gè)屬性,或該屬性的值是否等于特定值。
常用屬性:
- prefix: 屬性前綴。
- name: 屬性名。
- havingValue: 期望的值(如果匹配則加載)。
- matchIfMissing: 如果配置文件中沒寫這個(gè)屬性,默認(rèn)是否加載(true 為加載)。
?? 代碼示例:基于配置開關(guān)功能的 Bean
假設(shè)我們根據(jù)配置決定啟用 "短信通知" 還是 "郵件通知"。
1. 配置文件
feature: notification: sms # 改為 email 則加載 EmailService
2. 業(yè)務(wù) Bean 定義
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class NotificationConfig {
@Bean
// 當(dāng) feature.notification = email 時(shí)生效
@ConditionalOnProperty(prefix = "feature", name = "notification", havingValue = "email")
public NotificationService emailService() {
return new EmailNotificationService();
}
@Bean
// 當(dāng) feature.notification = sms 時(shí)生效
// matchIfMissing = true 表示如果不配這個(gè)配置,默認(rèn)也啟用 SMS
@ConditionalOnProperty(prefix = "feature", name = "notification", havingValue = "sms", matchIfMissing = true)
public NotificationService smsService() {
return new SmsNotificationService();
}
}?? 代碼示例:自定義 @Conditional (高階用法)
如果 @ConditionalOnProperty 無法滿足需求(比如判斷操作系統(tǒng)、判斷某個(gè)文件是否存在),可以使用 @Conditional。
// 1. 定義判斷邏輯
public class WindowsCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment().getProperty("os.name").contains("Windows");
}
}
// 2. 使用注解
@Bean
@Conditional(WindowsCondition.class) // 只有在 Windows 系統(tǒng)下才加載該 Bean
public CmdService cmdService() {
return new WindowsCmdService();
}4. 總結(jié)速查表
| 注解 | 作用域 | 核心作用 | 一句話記憶 |
|---|---|---|---|
| @ConfigurationProperties | 類 | 定義配置屬性與 POJO 的映射 | "把 yml 變成 Java 對象" |
| @EnableConfigurationProperties | 配置類 | 激活并注冊 @ConfigurationProperties 類 | "手動(dòng)開關(guān):啟用屬性對象" |
| @ConfigurationPropertiesScan | 啟動(dòng)類 | 自動(dòng)掃描并注冊屬性類 | "自動(dòng)開關(guān):掃碼全注冊" |
| @EnableAutoConfiguration | 啟動(dòng)類 | 開啟自動(dòng)裝配機(jī)制 (SPI) | "Spring Boot 的自動(dòng)魔法引擎" |
| @Conditional | 方法/類 | 自定義復(fù)雜的加載條件 | "萬能的 if 判斷" |
| @ConditionalOnProperty | 方法/類 | 基于配置屬性值決定是否加載 Bean | "根據(jù)開關(guān) (Toggle) 加載 Bean" |
到此這篇關(guān)于SpringBoot自動(dòng)裝配注解的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)SpringBoot自動(dòng)裝配注解內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java使用Callable和Future創(chuàng)建線程操作示例
這篇文章主要介紹了Java使用Callable和Future創(chuàng)建線程操作,結(jié)合實(shí)例形式分析了java使用Callable接口和Future類創(chuàng)建線程的相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下2019-09-09
Java web含驗(yàn)證碼及權(quán)限登錄實(shí)例代碼
這篇文章主要介紹了Java web含驗(yàn)證碼及權(quán)限登錄實(shí)例代碼,所用到的開發(fā)工具為myeclipse10,MySQL數(shù)據(jù)庫,具體實(shí)現(xiàn)代碼大家參考下本文吧2017-03-03
springboot jsp支持以及轉(zhuǎn)發(fā)配置方式
文章介紹了如何在Spring Boot項(xiàng)目中配置和使用JSP,并提供了一步一步的指導(dǎo),包括添加依賴、配置文件設(shè)置、控制器和視圖的使用2024-12-12
SpringCloud集成MybatisPlus實(shí)現(xiàn)MySQL多數(shù)據(jù)源配置方法
本文詳細(xì)介紹了SpringCloud集成MybatisPlus實(shí)現(xiàn)MySQL多數(shù)據(jù)源配置的方法,包括在application.properties中配置多數(shù)據(jù)源,配置MybatisPlus,創(chuàng)建Mapper接口和使用多數(shù)據(jù)源等步驟,此外,還解釋了每一個(gè)配置項(xiàng)目的含義,以便讀者更好地理解和應(yīng)用2024-10-10
MyBatis傳入?yún)?shù)為List對象的實(shí)現(xiàn)
這篇文章主要介紹了MyBatis傳入?yún)?shù)為List對象的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03

