Spring @Environment典型用法实战案例
作者:张紫娃
在使用Spring框架进行Java开发时,我们经常使用@Value和@Environment注解来注入配置文件中的值,这篇文章主要介绍了Spring @Environment典型用法的相关资料,需要的朋友可以参考下
简单说: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 { @Autowired private Environment environment; // ✅ 正确方式 // 使用 environment 对象获取属性或 profile }
结合 @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"); // 默认值
获取类型安全的属性值
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
总结
到此这篇关于Spring @Environment典型用法的文章就介绍到这了,更多相关Spring @Environment用法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!