有一些配置需要单独提出来时,如果是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();
}
网友评论