Spring如何將配置文件中的簡單值注入Bean中
Spring 提供了幾種優(yōu)雅的方式來將配置文件中的簡單值(如字符串、數(shù)字、布爾值等)注入到 Bean 中。
主要有兩種主流方法:
- 使用 @Value 注解:簡單直接,適合注入單個(gè)值。
- 使用 @ConfigurationProperties:類型安全,適合將一組相關(guān)的配置屬性映射到一個(gè)對(duì)象上,是 Spring Boot 官方推薦的方式。
方法一:使用@Value注解(簡單直接)
@Value 是最直接的方式,它可以從屬性文件、環(huán)境變量、系統(tǒng)屬性等地方讀取值并注入到字段中。
步驟 1:在application.properties中定義屬性
# 字符串 app.name=My Awesome Application # 數(shù)字 app.thread-pool.size=10 # 布爾值 app.feature.new-ui.enabled=true # 逗號(hào)分隔的列表 app.admin.emails=admin@example.com,support@example.com # 帶默認(rèn)值的屬性 (我們在代碼中處理) # app.description=... (假設(shè)這個(gè)屬性沒有被定義)
步驟 2:在 Bean 中使用@Value注入
@Value 使用 ${...} 占位符語法來引用屬性。
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct; // 使用 jakarta.* 如果是 Spring Boot 3+
import java.util.List;
@Component
public class AppConfig {
// 注入字符串
@Value("${app.name}")
private String appName;
// Spring 會(huì)自動(dòng)進(jìn)行類型轉(zhuǎn)換,將 "10" 轉(zhuǎn)換為 int
@Value("${app.thread-pool.size}")
private int threadPoolSize;
// 同樣,"true" 會(huì)被轉(zhuǎn)換為 boolean
@Value("${app.feature.new-ui.enabled}")
private boolean isNewUiEnabled;
// 注入一個(gè)列表 (Spring 會(huì)自動(dòng)按逗號(hào)分割)
@Value("${app.admin.emails}")
private List<String> adminEmails;
// 提供默認(rèn)值:如果屬性不存在,則使用冒號(hào)后面的默認(rèn)值
@Value("${app.description:This is a default description}")
private String appDescription;
// 打印出來看看結(jié)果
@PostConstruct
public void printConfig() {
System.out.println("Application Name: " + appName);
System.out.println("Thread Pool Size: " + threadPoolSize);
System.out.println("Is New UI Enabled: " + isNewUiEnabled);
System.out.println("Admin Emails: " + adminEmails);
System.out.println("Application Description: " + appDescription);
}
}
@Value 的優(yōu)點(diǎn):
- 非常簡單,用于注入少量、零散的配置時(shí)非常方便。
- 支持 SpEL(Spring Expression Language),功能強(qiáng)大,例如可以注入其他 Bean 的屬性值:
@Value("#{otherBean.someProperty}")。
@Value 的缺點(diǎn):
- 當(dāng)屬性很多時(shí),代碼會(huì)變得冗長和分散。
- 不是類型安全的。如果你在屬性文件中寫了一個(gè)非數(shù)字的值給
threadPoolSize,錯(cuò)誤只會(huì)在運(yùn)行時(shí)才會(huì)暴露。 - 重構(gòu)不友好(比如修改屬性前綴)。
方法二:使用@ConfigurationProperties(官方推薦)
這種方式將一組相關(guān)的配置屬性綁定到一個(gè)類型安全的 POJO(Plain Old Java Object)上。
步驟 1:在application.properties中定義屬性(與上面相同)
app.name=My Awesome Application app.thread-pool.size=10 app.feature.new-ui.enabled=true app.admin.emails=admin@example.com,support@example.com
步驟 2:創(chuàng)建一個(gè)配置屬性類
這個(gè)類就是一個(gè)普通的 Java 類,包含了與配置文件中屬性名對(duì)應(yīng)的字段。
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.List;
// 這個(gè)注解告訴 Spring,將 "app" 前綴的屬性綁定到這個(gè)類的字段上
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
private List<String> adminEmails;
// 注意:這里我們創(chuàng)建一個(gè)嵌套類來映射嵌套的屬性,結(jié)構(gòu)更清晰
private final ThreadPool threadPool = new ThreadPool();
private final Feature feature = new Feature();
// 嵌套類,用于映射 app.thread-pool.*
public static class ThreadPool {
private int size;
// Getter and Setter...
public int getSize() { return size; }
public void setSize(int size) { this.size = size; }
}
// 嵌套類,用于映射 app.feature.*
public static class Feature {
private final NewUi newUi = new NewUi();
public static class NewUi {
private boolean enabled;
// Getter and Setter...
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
}
public NewUi getNewUi() { return newUi; }
}
// 主類的 Getters and Setters...
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public List<String> getAdminEmails() { return adminEmails; }
public void setAdminEmails(List<String> adminEmails) { this.adminEmails = adminEmails; }
public ThreadPool getThreadPool() { return threadPool; }
public Feature getFeature() { return feature; }
}
注意:
- Spring Boot 會(huì)自動(dòng)將 kebab-case(如
thread-pool.size)或 snake_case(thread_pool.size)的屬性名映射到 camelCase(threadPool.size)的字段名。 - 必須提供標(biāo)準(zhǔn)的 Getters 和 Setters,Spring Boot 通過它們來設(shè)置值。
步驟 3:在主配置類中啟用這個(gè)屬性類
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
// 告訴 Spring Boot 啟用 AppProperties,并將其注冊為一個(gè) Bean
@EnableConfigurationProperties(AppProperties.class)
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
步驟 4:在任何其他 Bean 中注入和使用這個(gè)屬性對(duì)象
現(xiàn)在,你可以像注入任何其他 Service 一樣,注入整個(gè) AppProperties 對(duì)象。
import org.springframework.stereotype.Service;
@Service
public class MyBusinessService {
private final AppProperties appProperties;
// 通過構(gòu)造函數(shù)注入,非常清晰
public MyBusinessService(AppProperties appProperties) {
this.appProperties = appProperties;
}
public void doSomething() {
System.out.println("Running service for app: " + appProperties.getName());
if (appProperties.getFeature().getNewUi().isEnabled()) {
System.out.println("Using the new UI with thread pool size: " + appProperties.getThreadPool().getSize());
}
}
}
總結(jié):@Valuevs@ConfigurationProperties
| 特性 | @Value | @ConfigurationProperties (推薦) |
|---|---|---|
| 用途 | 注入單個(gè)、零散的值 | 將一組相關(guān)的配置綁定到一個(gè)對(duì)象 |
| 類型安全 | 運(yùn)行時(shí)檢查,弱類型 | 編譯時(shí)綁定(部分 IDE 支持),強(qiáng)類型 |
| 代碼組織 | 配置分散在多個(gè)類中 | 配置集中在一個(gè) POJO 中,結(jié)構(gòu)清晰 |
| 驗(yàn)證 | 不支持 JSR-303 驗(yàn)證 | 支持 @Validated 注解進(jìn)行數(shù)據(jù)校驗(yàn) |
| IDE 支持 | 弱(簡單的字符串跳轉(zhuǎn)) | 強(qiáng)大(在 .properties 文件中輸入時(shí)會(huì)有代碼提示和元數(shù)據(jù)支持) |
| 靈活性 | 支持 SpEL,更靈活 | 面向結(jié)構(gòu)化配置,更規(guī)范 |
最佳實(shí)踐:
- 優(yōu)先使用 @ConfigurationProperties。它讓你的代碼更健壯、更易于維護(hù)和測試。
- 只有當(dāng)你需要注入單個(gè)與其他配置無關(guān)的值,或者需要利用 SpEL 的強(qiáng)大功能時(shí),考慮使用 @Value。
到此這篇關(guān)于Spring如何將配置文件中的簡單值注入Bean中的文章就介紹到這了,更多相關(guān)Spring注入Bean內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
IntelliJ idea 如何生成動(dòng)態(tài)的JSON字符串(步驟詳解)
這篇文章主要介紹了IntelliJ idea 如何生成動(dòng)態(tài)的JSON字符串,本文分步驟給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08
java如何實(shí)現(xiàn)圖片轉(zhuǎn)化為數(shù)據(jù)流
這篇文章主要介紹了java如何實(shí)現(xiàn)圖片轉(zhuǎn)化為數(shù)據(jù)流,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01

