簡單說:Spring 里沒有直接叫 @Environment 的注解,更準確說常用的是 @Autowired 注入 Environment 對象,或者結合 @Value 配合 Environment 讀取配置 。
支持從以下來源讀取:
1、application.properties / .yaml
2、JVM 參數(如 -Dkey=value)
3、系統環境變量
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 {@Autowiredprivate Environment environment; // ? 正確方式// 使用 environment 對象獲取屬性或 profile
}
結合 @PropertySource 使用示例
@Configuration
@PropertySource("classpath:custom.properties")
public class AppConfig {@Autowiredprivate Environment env;@Beanpublic 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"); // 默認值
獲取類型安全的屬性值
Boolean featureEnabled = environment.getProperty("feature.enabled", Boolean.class, false);
獲取當前激活的 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.");
}// 或者使用更現代的寫法:
if (environment.acceptsProfiles(Profiles.of("dev"))) {// dev 環境邏輯
}
獲取所有 PropertySources(調試用途)
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 參數)
2、systemEnvironment(操作系統環境變量)
3、servletConfigInitParams(Web 配置參數)
4、自定義加載的 @PropertySource