SpringBoot獲取配置文件值和環(huán)境變量的方式
1. 配置文件基礎(chǔ)
Spring Boot 支持多種格式的配置文件:
application.propertiesapplication.ymlapplication.yaml
配置文件默認(rèn)加載順序:
file:./config/(項(xiàng)目根目錄下的config子目錄)file:./(項(xiàng)目根目錄)classpath:/config/(resources/config目錄)classpath:/(resources目錄)
2. 使用 @Value 注解獲取配置值
2.1 基本用法
@Component
public class ConfigService {
// 獲取普通配置值
@Value("${app.name}")
private String appName;
// 設(shè)置默認(rèn)值
@Value("${server.port:8080}")
private int port = 8080;
// 獲取布爾值
@Value("${app.enabled:true}")
private boolean enabled;
// 獲取列表值
@Value("${app.tags:java,spring}")
private List<String> tags;
// 獲取數(shù)組值
@Value("${app.servers}")
private String[] servers;
public void printConfig() {
System.out.println("App Name: " + appName);
System.out.println("Port: " + port);
System.out.println("Enabled: " + enabled);
System.out.println("Tags: " + Arrays.toString(tags.toArray()));
System.out.println("Servers: " + Arrays.toString(servers));
}
}
2.2 配置示例 (application.yml)
app:
name: MySpringBootApplication
enabled: true
tags: java,spring,boot
servers:
- server1
- server2
- server3
server:
port: 80803. 使用 @ConfigurationProperties 批量注入
3.1 創(chuàng)建配置類
@ConfigurationProperties(prefix = "app")
@Component
public class AppProperties {
private String name;
private boolean enabled;
private String version;
private Database database;
private List<String> features;
private Map<String, String> properties;
// 內(nèi)部類定義嵌套配置
public static class Database {
private String url;
private String username;
private String password;
private int maxConnections;
// getter 和 setter 方法
public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public int getMaxConnections() { return maxConnections; }
public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; }
}
// getter 和 setter 方法
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
public String getVersion() { return version; }
public void setVersion(String version) { this.version = version; }
public Database getDatabase() { return database; }
public void setDatabase(Database database) { this.database = database; }
public List<String> getFeatures() { return features; }
public void setFeatures(List<String> features) { this.features = features; }
public Map<String, String> getProperties() { return properties; }
public void setProperties(Map<String, String> properties) { this.properties = properties; }
}
3.2 啟用配置屬性
在主類或配置類上添加注解:
@SpringBootApplication
@EnableConfigurationProperties(AppProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
或者在 application.yml 中配置:
app:
name: MyApplication
enabled: true
version: 1.0.0
features:
- feature1
- feature2
- feature3
properties:
key1: value1
key2: value2
database:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: password
max-connections: 1004. 使用 Environment 接口
@Service
public class EnvironmentService {
@Autowired
private Environment environment;
public void getEnvironmentValues() {
// 獲取配置值
String appName = environment.getProperty("app.name");
String port = environment.getProperty("server.port");
String defaultPort = environment.getProperty("server.port", "8080");
// 獲取特定類型的值
Integer serverPort = environment.getProperty("server.port", Integer.class, 8080);
Boolean debugMode = environment.getProperty("debug", Boolean.class, false);
// 檢查屬性是否存在
if (environment.containsProperty("app.name")) {
System.out.println("App name exists: " + appName);
}
// 獲取所有活躍的配置文件
String[] activeProfiles = environment.getActiveProfiles();
String[] defaultProfiles = environment.getDefaultProfiles();
System.out.println("Active profiles: " + Arrays.toString(activeProfiles));
System.out.println("Default profiles: " + Arrays.toString(defaultProfiles));
}
}
5. 獲取環(huán)境變量
5.1 直接獲取系統(tǒng)環(huán)境變量
@Component
public class SystemEnvService {
public void getSystemEnvironment() {
// 方式1:通過(guò) System.getenv()
String homeDir = System.getenv("HOME");
String path = System.getenv("PATH");
String userName = System.getenv("USER");
// 方式2:通過(guò) Environment 接口
Environment env = new StandardEnvironment();
String homeFromEnv = env.getProperty("HOME");
// 方式3:通過(guò) @Value 注解
@Value("${HOME:#{null}}") // 注意:環(huán)境變量通常不以 $ 開頭
private String homePath;
System.out.println("Home directory: " + homeDir);
System.out.println("PATH: " + path);
System.out.println("User: " + userName);
}
}
5.2 通過(guò) Environment 獲取環(huán)境變量
@Service
public class EnvVariableService {
@Autowired
private Environment environment;
public void getEnvironmentVariables() {
// 獲取環(huán)境變量(注意:環(huán)境變量名通常大寫)
String dbHost = environment.getProperty("DB_HOST");
String dbPort = environment.getProperty("DB_PORT");
String secretKey = environment.getProperty("SECRET_KEY");
// 設(shè)置默認(rèn)值
String dbHostWithDefault = environment.getProperty("DB_HOST", "localhost");
System.out.println("DB Host: " + dbHost);
System.out.println("DB Port: " + dbPort);
System.out.println("Secret Key: " + secretKey);
}
}
6. 配置文件的 Profile 支持
6.1 不同環(huán)境的配置文件
application.yml(默認(rèn)配置)application-dev.yml(開發(fā)環(huán)境)application-test.yml(測(cè)試環(huán)境)application-prod.yml(生產(chǎn)環(huán)境)
6.2 使用 Profile 的配置類
@Configuration
@Profile("dev")
public class DevConfig {
@Bean
public String devDatabaseUrl() {
return "jdbc:h2:mem:devdb";
}
}
@Configuration
@Profile("!dev") // 非開發(fā)環(huán)境
public class ProdConfig {
@Bean
public String prodDatabaseUrl() {
return "jdbc:mysql://prod-server:3306/proddb";
}
}
7. 高級(jí)用法:條件化配置
7.1 使用 @ConditionalOnProperty
@Configuration
public class ConditionalConfig {
@Bean
@ConditionalOnProperty(name = "app.feature.enabled", havingValue = "true", matchIfMissing = false)
public FeatureService featureService() {
return new FeatureServiceImpl();
}
@Bean
@ConditionalOnProperty(name = "app.cache.type", havingValue = "redis", matchIfMissing = false)
public CacheService redisCacheService() {
return new RedisCacheService();
}
@Bean
@ConditionalOnProperty(name = "app.cache.type", havingValue = "memory", matchIfMissing = true)
public CacheService memoryCacheService() {
return new MemoryCacheService();
}
}
8. 配置驗(yàn)證
8.1 添加驗(yàn)證注解
@ConfigurationProperties(prefix = "app")
@Component
@Validated
public class ValidatedAppProperties {
@NotBlank(message = "應(yīng)用名稱不能為空")
private String name;
@Min(value = 1, message = "端口號(hào)必須大于0")
@Max(value = 65535, message = "端口號(hào)不能超過(guò)65535")
private int port;
@Pattern(regexp = "^\\d+\\.\\d+\\.\\d+$", message = "版本號(hào)格式不正確,應(yīng)為 x.y.z 格式")
private String version;
@AssertTrue(message = "應(yīng)用必須啟用才能正常工作")
private boolean enabled;
// getter 和 setter 方法...
}
9. 實(shí)際應(yīng)用示例
9.1 完整的服務(wù)類
@Service
@Slf4j
public class ConfigurationManager {
@Value("${app.name:DefaultApp}")
private String appName;
@Value("${app.version:1.0.0}")
private String appVersion;
@Autowired
private Environment environment;
@Autowired
private AppProperties appProperties;
public void displayAllConfigs() {
log.info("=== 應(yīng)用配置信息 ===");
log.info("App Name: {}", appName);
log.info("App Version: {}", appVersion);
log.info("=== 通過(guò) Environment 獲取 ===");
log.info("Server Port: {}", environment.getProperty("server.port"));
log.info("Active Profiles: {}", Arrays.toString(environment.getActiveProfiles()));
log.info("=== 通過(guò) @ConfigurationProperties 獲取 ===");
log.info("App Properties Name: {}", appProperties.getName());
log.info("App Properties Enabled: {}", appProperties.isEnabled());
log.info("Database URL: {}", appProperties.getDatabase().getUrl());
log.info("=== 環(huán)境變量示例 ===");
log.info("JAVA_HOME: {}", System.getenv("JAVA_HOME"));
log.info("OS: {}", System.getProperty("os.name"));
}
public String getProperty(String key) {
return environment.getProperty(key);
}
public String getProperty(String key, String defaultValue) {
return environment.getProperty(key, defaultValue);
}
public <T> T getProperty(String key, Class<T> targetType, T defaultValue) {
return environment.getProperty(key, targetType, defaultValue);
}
}
10. 最佳實(shí)踐建議
10.1 配置命名規(guī)范
# 推薦的命名方式
my-app:
service:
timeout: 30s
retry-count: 3
database:
connection-timeout: 20s
pool-size: 10
# 避免駝峰命名(雖然也支持)
myAppServiceTimeout: 30s10.2 安全敏感配置
// 對(duì)于密碼等敏感信息,建議使用配置解密
@ConfigurationProperties(prefix = "app.security")
@Component
public class SecurityProperties {
private String encryptedPassword;
// 不直接暴露密碼字段,而是提供解密方法
public String getDecryptedPassword() {
// 實(shí)現(xiàn)解密邏輯
return decrypt(encryptedPassword);
}
private String decrypt(String encryptedValue) {
// 解密實(shí)現(xiàn)
return encryptedValue; // 簡(jiǎn)化示例
}
}
11. 配置刷新機(jī)制
對(duì)于需要?jiǎng)討B(tài)刷新的配置,可以結(jié)合 Spring Cloud Config 或使用 @RefreshScope:
@RestController
@RefreshScope
public class ConfigController {
@Value("${app.message:Hello Default}")
private String message;
@GetMapping("/message")
public String getMessage() {
return message;
}
}
12、環(huán)境變量
程序啟動(dòng)時(shí)的命令行參數(shù)
- java設(shè)置方式
java -jar app.jar --jasypt.encryptor.password=salt
IDEA設(shè)置方式

讀取方式
System.getenv(jasypt.encryptor.password);
程序啟動(dòng)時(shí)的應(yīng)用環(huán)境變量
- java啟動(dòng)設(shè)置方式
java -jar app.jar -Djasypt.encryptor.password=salt
IDEA設(shè)置方式

讀取方式
System.getProperty(jasypt.encryptor.password);
總結(jié)
Spring Boot 提供了多種靈活的方式來(lái)獲取配置值和環(huán)境變量:
- @Value: 適用于簡(jiǎn)單的單個(gè)值注入
- @ConfigurationProperties: 適用于復(fù)雜對(duì)象的批量配置
- Environment: 適用于程序化訪問(wèn)配置值
- Profile: 適用于不同環(huán)境的差異化配置
- 條件化配置: 適用于基于條件的配置加載
以上就是SpringBoot獲取配置文件值和環(huán)境變量的方式的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot配置文件值和環(huán)境變量的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
rabbitmq的消息持久化處理開啟,再關(guān)閉后,消費(fèi)者啟動(dòng)報(bào)錯(cuò)問(wèn)題
這篇文章主要介紹了rabbitmq的消息持久化處理開啟,再關(guān)閉后,消費(fèi)者啟動(dòng)報(bào)錯(cuò)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11
SSM使用mybatis分頁(yè)插件pagehepler實(shí)現(xiàn)分頁(yè)示例
本篇文章主要介紹了SSM使用mybatis分頁(yè)插件pagehepler實(shí)現(xiàn)分頁(yè)示例,使用分頁(yè)插件的原因,簡(jiǎn)化了sql代碼的寫法,實(shí)現(xiàn)較好的物理分頁(yè),非常具有實(shí)用價(jià)值,需要的朋友可以參考下2018-03-03
Java Socket實(shí)現(xiàn)聊天室附1500行源代碼
Socket是應(yīng)用層與TCP/IP協(xié)議族通信的中間軟件抽象層,它是一組接口。本篇文章手把手帶你通過(guò)Java Socket來(lái)實(shí)現(xiàn)自己的聊天室,大家可以在過(guò)程中查缺補(bǔ)漏,溫故而知新2021-10-10
Spring中IoC優(yōu)點(diǎn)與缺點(diǎn)解析
這篇文章主要為大家詳細(xì)解析了Spring中IoC優(yōu)點(diǎn)與缺點(diǎn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11
SpringBoot disruptor高性能隊(duì)列使用
這篇文章主要介紹了SpringBoot disruptor高性能隊(duì)列使用,Disruptor是英國(guó)外匯交易公司LMAX開發(fā)的一個(gè)高性能隊(duì)列,研發(fā)的初衷是解決內(nèi)存隊(duì)列的延遲問(wèn)題2023-02-02
java導(dǎo)出數(shù)據(jù)庫(kù)中Excel表格數(shù)據(jù)的方法
這篇文章主要為大家詳細(xì)介紹了java導(dǎo)出數(shù)據(jù)庫(kù)中Excel表格數(shù)據(jù)的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08
Java使用CompletableFuture進(jìn)行非阻塞IO詳解
這篇文章主要介紹了Java使用CompletableFuture進(jìn)行非阻塞IO詳解,CompletableFuture是Java中的一個(gè)類,用于支持異步編程和處理異步任務(wù)的結(jié)果,它提供了一種方便的方式來(lái)處理異步操作,并允許我們以非阻塞的方式執(zhí)行任務(wù),需要的朋友可以參考下2023-09-09
MyBatis-Plus主鍵生成策略的實(shí)現(xiàn)方法
MyBatis-Plus提供了多種主鍵生成策略,包括自增、UUID、Redis和雪花算法,本文就來(lái)介紹一下,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-12-12

