一、核心功能与作用
@PropertySource
是Spring框架中用于加载外部配置文件的核心注解,主要作用是将属性文件(如.properties
、.yml
)的键值对加载到Spring的Environment
环境中,实现配置与代码的解耦。其核心价值包括:
-
外部化配置管理:将数据库连接、API密钥等敏感信息从代码中剥离,存储到外部文件。
-
多环境适配:支持按环境加载不同配置文件(如开发、生产环境)。
-
动态注入:结合
@Value
注解或Environment
接口直接获取配置值。
二、注解属性与语法
@PropertySource
的源码定义如下:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(PropertySources.class)
public @interface PropertySource {
String name() default ""; // 属性源名称(默认自动生成)
String[] value(); // 文件路径(支持classpath:、file:等协议)
boolean ignoreResourceNotFound() default false; // 忽略文件未找到错误
String encoding() default ""; // 文件编码(解决中文乱码问题)
Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class; // 自定义工厂类
}
关键属性解析:
- value
指定配置文件路径,支持多种协议:@PropertySource("classpath:config/db.properties") // 类路径 @PropertySource("file:/etc/app/config.yml") // 文件系统路径 @PropertySource("https://config-server.com/env.properties") // 远程资源
- ignoreResourceNotFound
设置为true
时,若文件不存在不会抛出异常(默认false
,严格模式)。 - factory
自定义属性源工厂,用于解析非标准格式(如YAML、JSON)的配置文件。
三、使用场景与最佳实践
-
基础用法:加载单一配置文件
@Configuration @PropertySource("classpath:application.properties") public class AppConfig { @Value("${db.url}") private String dbUrl; }
- 文件内容自动注入
Environment
,通过@Value("${key}")
或environment.getProperty("key")
获取。
- 文件内容自动注入
-
多文件与动态环境配置
@Configuration @PropertySources({ @PropertySource("classpath:default.properties"), @PropertySource("classpath:env/${spring.profiles.active}.properties") }) public class MultiEnvConfig {}
-
通过
${spring.profiles.active}
动态加载环境相关配置。 -
优先级规则:后加载的文件覆盖先加载的同名属性。
-
-
自定义配置格式支持(如YAML)
public class YamlPropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(resource.getResource()); Properties properties = factory.getObject(); return new PropertiesPropertySource(name, properties); } } // 使用示例 @Configuration @PropertySource(value = "classpath:config.yml", factory = YamlPropertySourceFactory.class) public class YamlConfig {}
- 通过实现
PropertySourceFactory
接口解析非标准格式文件。
- 通过实现
四、底层原理与执行流程
- 加载时机
在Spring容器启动阶段,ConfigurationClassPostProcessor
会扫描所有@Configuration
类,解析@PropertySource
注解。 - 处理流程
-
资源定位:根据
value
属性查找文件。 -
资源解析:使用默认或自定义的
PropertySourceFactory
将文件转换为PropertySource
对象。 -
注册环境:将生成的
PropertySource
添加到Environment
的PropertySources
列表中。
-
五、注意事项与常见问题
-
编码问题
若配置文件含中文,需显式指定encoding="UTF-8"
。 -
资源路径匹配
-
使用
classpath*:
前缀可扫描多个JAR包中的同名文件。 -
支持Ant风格路径模式(如
config/*.properties
)。
-
-
与
@ConfigurationProperties
配合
更推荐结合@ConfigurationProperties
实现类型安全的配置绑定:@Configuration @PropertySource("classpath:redis.properties") @ConfigurationProperties(prefix = "redis") public class RedisConfig { private String host; private int port; }
总结
@PropertySource
通过标准化配置加载机制,使Spring应用具备高度灵活的外部化配置能力。开发者可根据需求选择基础用法或通过自定义工厂扩展,同时需关注属性优先级、编码规范及多环境适配等关键点。对于复杂场景,建议结合@Profile
和@Conditional
实现动态配置管理。
spring5.x讲解介绍
netty与tomcat的比较