加载自定义yml文件

261 阅读1分钟
  1. 在classpath下添加一个自定义配置文件

image.png

#配置文件内容大概是下面代码,xxx是prefix
xxx:
    map:
      key: value
    ranks:
    - bananas
    - apple
    - orange
  1. 首先定义一个配置类,并且DefaultPropertySourceFactory重写方法。
public class YamlPropertySourceFactory extends DefaultPropertySourceFactory{
	@Override
	public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
		 if (resource == null) {
	            return super.createPropertySource(name, resource);
	        }
	        List<PropertySource<?>> propertySourceList = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
	        if (!propertySourceList.isEmpty()) {
	            return propertySourceList.iterator().next();
	        }
		return super.createPropertySource(name, resource);
	}
}
  1. 在目标类的上面加入如下一些注解,@PropertySource中的value为加载文件的位置,factory为你重写的类。@ConfigurationProperties(prefix="xxx")中的prefix为配置文件里面的prefix前缀
@PropertySource(value="classpath:xxx.yml", encoding="UTF-8",factory=YamlPropertySourceFactory.class)
@ConfigurationProperties(prefix="xxx")
@Component
public class RankVo {
	private Set<String> ranks;
	private Set<String> grades;
	private HashMap<String, String> map;
}
  1. 单元测试,打印配置内容
@SpringBootTest
public class AppliactionTest{
    @Autowired
    private RankVo rankVo;
    @Test
    public void test() {
        System.out.print(rankVo.ranks)
    }
}