@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;}}