Spring属性源(PropertySource)
外观
Spring属性源(PropertySource)[编辑 | 编辑源代码]
Spring属性源(PropertySource)是Spring框架中用于管理应用程序配置属性的核心抽象,它提供了一种统一的方式来访问不同来源(如.properties文件、环境变量、系统属性等)的配置数据。通过属性源机制,开发者可以灵活地组织、覆盖和扩展应用程序的配置。
核心概念[编辑 | 编辑源代码]
属性源定义[编辑 | 编辑源代码]
在Spring中,PropertySource
是一个抽象类(位于org.springframework.core.env
包),其子类表示具体的属性来源。每个属性源包含一组键值对,例如:
application.properties
文件中的配置- 操作系统环境变量
- JVM系统属性(
-D
参数)
属性源层级[编辑 | 编辑源代码]
Spring会按照以下优先级顺序(从高到低)解析属性:
- JVM系统属性(
-D
) - 环境变量
- 配置文件(如
application.properties
)
可通过以下Mermaid图表示层级关系:
代码示例[编辑 | 编辑源代码]
基础用法[编辑 | 编辑源代码]
以下示例展示如何通过@Value
注解注入属性:
@Configuration
public class AppConfig {
@Value("${app.name}") // 从属性源读取值
private String appName;
@Bean
public void printConfig() {
System.out.println("Application Name: " + appName);
}
}
对应的application.properties
:
app.name=MySpringApp
输出结果:
Application Name: MySpringApp
自定义属性源[编辑 | 编辑源代码]
实现自定义属性源需要继承PropertySource
:
public class CustomPropertySource extends PropertySource<String> {
private Map<String, String> properties = new HashMap<>();
public CustomPropertySource() {
super("customPropertySource");
properties.put("custom.key", "value123");
}
@Override
public Object getProperty(String name) {
return properties.get(name);
}
}
注册自定义属性源:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
ConfigurableEnvironment env = context.getEnvironment();
env.getPropertySources().addFirst(new CustomPropertySource());
System.out.println("Custom property: " + env.getProperty("custom.key"));
}
}
输出结果:
Custom property: value123
高级特性[编辑 | 编辑源代码]
属性覆盖规则[编辑 | 编辑源代码]
当多个属性源包含相同键时,Spring会按照以下规则处理:
动态属性更新[编辑 | 编辑源代码]
通过@RefreshScope
(Spring Cloud Config)可实现动态属性更新:
@RefreshScope
@RestController
public class ConfigController {
@Value("${dynamic.property}")
private String dynamicProp;
}
实际应用场景[编辑 | 编辑源代码]
多环境配置[编辑 | 编辑源代码]
典型的多环境配置方案:
1. application-dev.properties
(开发环境)
2. application-prod.properties
(生产环境)
通过激活不同的Spring Profile加载对应配置:
java -jar app.jar --spring.profiles.active=prod
敏感信息管理[编辑 | 编辑源代码]
将密码等敏感信息存储在环境变量中而非配置文件中:
db.password=${DB_PASSWORD}
最佳实践[编辑 | 编辑源代码]
- 优先使用
application-{profile}.properties
而非条件注解 - 敏感数据应通过环境变量或密钥管理服务注入
- 避免在属性源中使用硬编码路径(如
c:\path\to\file
)