Spring @Environment典型用法實戰(zhàn)案例
簡單說:Spring 里沒有直接叫 @Environment 的注解,更準(zhǔn)確說常用的是 @Autowired 注入 Environment 對象,或者結(jié)合 @Value 配合 Environment 讀取配置 。
支持從以下來源讀取:
1、application.properties / .yaml
2、JVM 參數(shù)(如 -Dkey=value)
3、系統(tǒng)環(huán)境變量
4、自定義 @PropertySource
獲取Environment實例
使用 @Autowired 注入 Environment 接口實例
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class MyComponent {
@Autowired
private Environment environment; // ? 正確方式
// 使用 environment 對象獲取屬性或 profile
}
結(jié)合 @PropertySource 使用示例
@Configuration
@PropertySource("classpath:custom.properties")
public class AppConfig {
@Autowired
private Environment env;
@Bean
public MyService myService() {
String customValue = env.getProperty("custom.key");
return new MyService(customValue);
}
}
使用Environment實例
獲取配置屬性值
String dbUrl = environment.getProperty("spring.datasource.url");
String appName = environment.getProperty("app.name", "defaultAppName"); // 默認(rèn)值
獲取類型安全的屬性值
Boolean featureEnabled = environment.getProperty("feature.enabled", Boolean.class, false);
獲取當(dāng)前激活的 Profile
String[] activeProfiles = environment.getActiveProfiles();
for (String profile : activeProfiles) {
System.out.println("Active Profile: " + profile);
}
判斷是否匹配某個 Profile
if (environment.acceptsProfiles("dev")) {
System.out.println("Running in development mode.");
}
// 或者使用更現(xiàn)代的寫法:
if (environment.acceptsProfiles(Profiles.of("dev"))) {
// dev 環(huán)境邏輯
}
獲取所有 PropertySources(調(diào)試用途)
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.PropertySource;
((AbstractEnvironment) environment).getPropertySources().forEach(ps -> {
System.out.println("Property Source: " + ps.getName());
});
常見 PropertySource 包括:
1、systemProperties(JVM 參數(shù))
2、systemEnvironment(操作系統(tǒng)環(huán)境變量)
3、servletConfigInitParams(Web 配置參數(shù))
4、自定義加載的 @PropertySource
總結(jié)
到此這篇關(guān)于Spring @Environment典型用法的文章就介紹到這了,更多相關(guān)Spring @Environment用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring Boot使用yml格式進(jìn)行配置的方法
很多springboot項目使用的是yml格式,主要目的是方便對讀懂其他人的項目,下面小編通過本文給大家分享Spring Boot使用yml格式進(jìn)行配置的方法,需要的朋友參考下吧2018-04-04
springboot整合規(guī)則引擎(liteflow)使用方式
這篇文章主要介紹了springboot整合規(guī)則引擎(liteflow)使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-07-07
IntelliJ IDEA 2017.1.4 x64配置步驟(介紹)
下面小編就為大家?guī)硪黄狪ntelliJ IDEA 2017.1.4 x64配置步驟(介紹)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06
springboot @ConditionalOnMissingBean注解的作用詳解
這篇文章主要介紹了springboot @ConditionalOnMissingBean注解的作用詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08

