SpringBoot加载自定义yml文件

时间:2023-03-09 22:02:00
SpringBoot加载自定义yml文件

自定义配置文件(跟SpringBoot的application.yml同一目录下):

nlu-parse-rule:
title: "NLU响应结果解析规则"
desc: "解析NLU的识别文本(JSON)构建响应URL,注意当前yaml配置中key不用到下划线"
rules:
- busiDesc: "能耗业务1"
busiCode: "nh1"
firstMarch:
- $.store.bicycle.color|red|=
- $.appkey|7kfo5mdq5xnf6ofkfh76xda7lbccqgi7gzfhakyq|=
secondMatch:
- $.store.bicycle.color|NULL|<>
- $.store.bicycle.color|NULL|<>
returnValue: # url中占位符的真实替换值
- key1|$.store.bicycle.color
- key2|$.store.bicycle.color
- key3|$.store.bicycle.color

映射为对象,代码如下:

 @Component
@PropertySource(value= {"classpath:rules.yml"})
@ConfigurationProperties(prefix = "nlu-parse-rule")
@Data
public class NluRuleProperties {
private String title;
private String desc;
private List<NluRuleConfig> rules;
}

调试发现竟然不识别,

@PropertySource 不支持yml文件的对象转换,原因如下,看源码:他的默认构造工厂是PropertySourceFactory

 @Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(PropertySources.class)
public @interface PropertySource {
String name() default ""; String[] value(); boolean ignoreResourceNotFound() default false; String encoding() default ""; Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;
}

而PropertySourceFactory默认就一个实现:实现properties配置文件的加载解析

public class DefaultPropertySourceFactory implements PropertySourceFactory {
public DefaultPropertySourceFactory() {
} public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
return name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource);
}
}

因此,我们只要实现一个yml文件的工厂类即可,参考:https://mdeinum.github.io/2018-07-04-PropertySource-with-yaml-files/

代码实现:

 public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
Properties propertiesFromYaml = loadYamlIntoProperties(resource);
String sourceName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
} private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
} catch (IllegalStateException e) {
// for ignoreResourceNotFound
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException)
throw (FileNotFoundException) e.getCause();
throw e;
}
}
}

搞定!测试通过。