javascript
springboot yml怎么建常量_Springboot中加载自定义的yml配置文件
有一些配置需要單獨提出來時,如果是properties文件可以@PropertySource注解直接進行加載,但如果是yml文件就需要進行處理
1、創建你的配置文件,比如config.yml,寫入配置項
2、創建配置類,并加載配置文件
@Component
@Data
@Configuration
@PropertySource(value = {"classpath:/config.yml"}, factory = CompositePropertySourceFactory.class)
public class MyConfig {
@Value("${query.pageSize}")
public int pageSize;
}
3、自定義CompositePropertySourceFactory來加載yml文件
這里有個屬性叫factory,默認的factory是DefaultPropertySourceFactory,默認值加載properties文件
我們只需要繼承這個類,對其擴展即可
public class CompositePropertySourceFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource> createPropertySource(String name, EncodedResource resource)
throws IOException {
String sourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename());
if (!resource.getResource().exists()) {
// return an empty Properties
return new PropertiesPropertySource(sourceName, new Properties());
} else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
Properties propertiesFromYaml = loadYaml(resource);
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
} else {
return super.createPropertySource(name, resource);
}
}
/**
* load yaml file to properties
*
* @param resource
* @return
* @throws IOException
*/
private Properties loadYaml(EncodedResource resource) throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
}
總結
以上是生活随笔為你收集整理的springboot yml怎么建常量_Springboot中加载自定义的yml配置文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: angular 标准目录结构_Angul
- 下一篇: dockerfile安装yum_Dock