欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring如何將配置文件中的簡單值注入Bean中

 更新時(shí)間:2025年07月11日 08:31:43   作者:冰糖心書房  
Spring 提供了幾種優(yōu)雅的方式來將配置文件中的簡單值(如字符串、數(shù)字、布爾值等)注入到 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)文章

  • Java模擬并解決緩存穿透問題

    Java模擬并解決緩存穿透問題

    這篇文章主要介紹了Java模擬并解決緩存穿透問題,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下
    2019-08-08
  • springboot連接Redis的教程詳解

    springboot連接Redis的教程詳解

    這篇文章主要介紹了springboot連接Redis的教程詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-03-03
  • Java探索之string字符串的應(yīng)用代碼示例

    Java探索之string字符串的應(yīng)用代碼示例

    這篇文章主要介紹了Java探索之string字符串的應(yīng)用代碼示例,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-10-10
  • spring之Bean的生命周期詳解

    spring之Bean的生命周期詳解

    本篇文章主要介紹了spring之Bean的生命周期詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-05-05
  • IntelliJ idea 如何生成動(dòng)態(tài)的JSON字符串(步驟詳解)

    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ù)流

    這篇文章主要介紹了java如何實(shí)現(xiàn)圖片轉(zhuǎn)化為數(shù)據(jù)流,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • 關(guān)于線程池異步線程中再次獲取線程池資源的問題

    關(guān)于線程池異步線程中再次獲取線程池資源的問題

    這篇文章主要介紹了關(guān)于線程池異步線程中再次獲取線程池資源的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • Java 配置加載機(jī)制詳解及實(shí)例

    Java 配置加載機(jī)制詳解及實(shí)例

    這篇文章主要介紹了Java 配置加載機(jī)制詳解及實(shí)例的相關(guān)資料,需要的朋友可以參考下
    2016-09-09
  • java中Hutool包的常用方法總結(jié)

    java中Hutool包的常用方法總結(jié)

    這篇文章主要為大家詳細(xì)介紹了java在工作中中Hutool包的一些常用方法總結(jié),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-12-12
  • SpringBoot中的@Inherited注解詳解

    SpringBoot中的@Inherited注解詳解

    這篇文章主要介紹了SpringBoot中的@Inherited注解詳解,@Inherited是一個(gè)標(biāo)識(shí),用來修飾注解,如果一個(gè)類用上了@Inherited修飾的注解,那么其子類也會(huì)繼承這個(gè)注解,需要的朋友可以參考下
    2023-08-08

最新評(píng)論