@PropertySource可将配置文件加载到内存,时间有限说干的,@PropertySource注解有4个参数,其中value表示要加载文件的路径,这个参数不支持通配符。还有一个参数PropertySourceFactory是加载配置文件的工厂,这两个参数配合使用可以实现标题的功能,代码如下:
待加载的配置文件如下:
配置类如下:
@Configuration
@PropertySource(value = {"classpath:executePath/**_${mydemo.ymlparam:clickhouse}.properties"},encoding = "utf-8",factory = EngineSqlConfigSource.class,ignoreResourceNotFound = true
)
@Slf4j
public class EngineSqlConfig {@Autowiredprivate Environment environment;//获取配置文件中参数public String getProperty(String key, String defaultValue) {return this.environment.getProperty(key, defaultValue);}public String getPropertyNotEmpty(String key) {String value = this.environment.getProperty(key);if (StringUtil.isEmpty(value)) {log.error("配置项未配置,{}",key);return value;} else {return value;}}
}
工厂类如下
@Slf4j
public class EngineSqlConfigSource implements PropertySourceFactory {@Overridepublic PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {Properties props = new Properties();//按路径加载配置文件ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();Resource[] resources = resolver.getResources(((ClassPathResource) resource.getResource()).getPath());if (ArrayUtil.isEmpty(resources)) {return new PropertiesPropertySource("mainInfo", props);}for (int i = 0; i < resources.length; i++) {PropertiesLoaderUtils.fillProperties(props, resources[i]);}PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource("mainInfo", props);return propertiesPropertySource;}}