首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring Boot 配置文件深度解析:自定義屬性、參數引用、隨機值、命令行覆蓋與多環境隔離

     編輯:Java 相關知識

核心配置文件

Spring Boot 以 application.properties (或 .yml) 替代傳統 XML,支援模組化 Starter 自動配置。

1. 自定義屬性與 @Value 注入

# application.properties
com.example.blog.name=程序猿DD
com.example.blog.title=Spring Boot教程
@Component
public class BlogProperties {
    @Value("${com.example.blog.name}")
    private String name;

    @Value("${com.example.blog.title}")
    private String title;
    // getter/setter
}
@SpringBootTest
class ApplicationTests {
    @Autowired BlogProperties props;
    @Test void test() {
        assertEquals("程序猿DD", props.getName());
        assertEquals("Spring Boot教程", props.getTitle());
    }
}

2. 參數間引用 (置換)

com.example.blog.name=程序猿DD
com.example.blog.title=Spring Boot教程
com.example.blog.desc=${com.example.blog.name}正在努力寫《${com.example.blog.title}》

結果:desc = "程序猿DD正在努力寫《Spring Boot教程》"

3. 隨機值生成

# 隨機字符串 (UUID)
com.example.value=${random.value}
# 隨機 int
com.example.number=${random.int}
# 隨機 long
com.example.bignumber=${random.long}
# 0-9 隨機 int
com.example.test1=${random.int(10)}
# 10-19 隨機 int
com.example.test2=${random.int[10,20]}

適用場景:測試端口、生成密鑰、模擬數據。

4. 命令行參數覆蓋

java -jar app.jar --server.port=8888
  • -- 前綴標識配置屬性覆蓋
  • 等價於在 application.properties 寫 server.port=8888
  • 優先級:**命令行 > 環境變量 > 配置文件 > 默認值**

安全:禁用命令行覆蓋

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.setAddCommandLineProperties(false); // 禁用
        app.run(args);
    }
}

5. 多環境配置隔離

命名規範

application-dev.properties    # 開發環境
application-test.properties   # 測試環境
application-prod.properties   # 生產環境

啟用方式

# application.properties 指定默認
spring.profiles.active=dev
  • 各環境文件只覆蓋差異配置 (如 DB 地址、端口)
  • 通用配置放在 application.properties

命令行切換環境

java -jar app.jar --spring.profiles.active=test  # 啟用 test 環境
java -jar app.jar --spring.profiles.active=prod  # 啟用 prod 環境

實戰驗證

# dev: server.port=1111
# test: server.port=2222
# prod: server.port=3333

java -jar app.jar                    → 啟動端口 1111 (dev)
java -jar app.jar --spring.profiles.active=test → 啟動端口 2222
java -jar app.jar --spring.profiles.active=prod → 啟動端口 3333

6. 進階:YAML 格式支援

# application.yml
com:
  example:
    blog:
      name: 程序猿DD
      title: Spring Boot教程
      desc: ${com.example.blog.name}正在努力寫《${com.example.blog.title}》

spring:
  profiles:
    active: dev

最佳實踐總結

  1. application.properties 放**通用配置** + spring.profiles.active=dev 默認環境
  2. application-{profile}.properties 放**環境差異配置** (DB、Redis、端口、第三方服務地址)
  3. 啟動時用 --spring.profiles.active=xxx 切換環境,**不修改代碼/重新打包**
  4. 敏感配置 (密碼、密鑰) 用**環境變量**或**配置中心** (Nacos/Apollo),不入倉庫
  5. 善用 @ConfigurationProperties 類型安全綁定,替代分散的 @Value
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved