如何配置@PropertySource加载路径下匹配通配符的所有properties文件
@PropertySource通配符加载匹配规则配置文件的实现说明
Spring原生的@PropertySource注解默认不支持Ant风格通配符路径匹配,你示例里的两种写法在原生场景下无法生效,启动时会抛出资源不存在的异常。
可落地的实现方式
- 自定义PropertySourceFactory实现通配符解析
这是兼容原生Spring环境的通用方案,核心是借助Spring内置的路径匹配解析器批量识别符合规则的配置文件,再统一注册到Spring环境中:- 先编写自定义的属性源工厂类:
public class WildcardPropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(); String location = resource.getResource().getURL().toString(); Resource[] matchedResources = resourceResolver.getResources(location); CompositePropertySource compositeSource = new CompositePropertySource( StringUtils.hasText(name) ? name : "wildcardLoadedProperties" ); PropertiesPropertySourceFactory defaultFactory = new PropertiesPropertySourceFactory(); for (Resource matchedRes : matchedResources) { compositeSource.addPropertySource( defaultFactory.createPropertySource(null, new EncodedResource(matchedRes, resource.getCharset())) ); } return compositeSource; } }- 在
@PropertySource注解上指定自定义工厂,即可使用通配符路径:
// 加载所有以_config.properties结尾的配置 @PropertySource( value = "classpath:*_config.properties", factory = WildcardPropertySourceFactory.class ) // 加载指定目录下所有.properties配置 @PropertySource( value = "classpath:somefolder/*.properties", factory = WildcardPropertySourceFactory.class ) - Spring Boot环境简化方案
如果你的项目是Spring Boot应用,不需要自定义工厂,直接在主配置文件里通过spring.config.import配置项即可实现通配符批量引入:spring.config.import=classpath:*_config.properties,classpath:somefolder/*.properties
注意:通配符加载多配置文件时,要留意同key配置项的覆盖规则,匹配到的资源加载顺序受文件构建顺序、classpath顺序影响,建议不要在多个匹配到的配置文件里定义重复的配置key,避免出现配置值不符合预期的问题。
内容的提问来源于stack exchange,提问作者Alfredo Morales
相关产品推荐
相关产品推荐

