简单说: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