- 在classpath下添加一个自定义配置文件

xxx:
map:
key: value
ranks:
- bananas
- apple
- orange
- 首先定义一个配置类,并且
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);
}
}
- 在目标类的上面加入如下一些注解,
@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;
}
- 单元测试,打印配置内容
@SpringBootTest
public class AppliactionTest{
@Autowired
private RankVo rankVo;
@Test
public void test() {
System.out.print(rankVo.ranks)
}
}