添加依赖
由于是要读取yaml文件,需要添加yaml的依赖
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.26</version>
</dependency>
YamlPropertySourceFactory
package com.edu.spring5;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import java.io.IOException;
import java.util.Properties;
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
yamlPropertiesFactoryBean.setResources(resource.getResource());
Properties properties = yamlPropertiesFactoryBean.getObject();
return name != null ? new PropertiesPropertySource(name, properties) : new PropertiesPropertySource(resource.getResource().getFilename(), properties);
}
}
在Spring4.3 之前要使用PropertySource,因为DefaultPropertySourceFactory,要注入PropertySourcePlaceHolderConfigurer 这个类
@Bean
public PropertySourcesPlaceholderConfigurer propertySourceConfigurer(){
return new PropertySourcesPlaceholderConfigurer();
}
参考文献
PropertySource注解基本使用
PropertySource与Spring版本
Spring4.3版本后的执行逻辑
xml与properties文件分析ne
PropertySourceFactory分析
自定义PropertySourceFactory读取yaml
网友评论