此文关于 yml 部分参考了此文:@PropertySource加载yml
1.首先写一个 ConfigurationFactory 类,作为 配置属性源工厂:
public class ConfigurationFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource)
throws IOException {
// 指定配置路径中的文件名
String filename = resource.getResource().getFilename() == null ?
"" : resource.getResource().getFilename();
// 资源为空,则会抛出异常
resource.getInputStream();
// 配置文件为 properties 文件,调用原逻辑
if ( resource == null
|| filename.endsWith(".properties"))
return super.createPropertySource( name, resource);
// yml文件 或 yaml文件,则使用yaml属性源加载器加载并返回标准属性源
else if ( filename.endsWith(".yml")
|| filename.endsWith(".yaml"))
return new YamlPropertySourceLoader()
.load( resource.getResource().getFilename(), resource.getResource()).get(0);
// 非以上情况,则直接抛出异常,提示格式错误
else
throw new IOException("file format error! only support: properties, yml, yaml!");
}
}
2.在 接收配置的bean 上加注解(此处业务需要,用的Hashtable,接收类型只要是实现了Map接口即可):
/**
* 配置结构类
*/
// factory 指定刚才写的 ConfigurationFactory.class
@PropertySource(value = {"classpath:user.yml", "classpath:user.yaml", "classpath:user.properties"}, encoding = "utf-8", factory = ConfigurationFactory.class)
@ConfigurationProperties(prefix = "user")
@Component
class UserConfig implements Cloneable {
private Hashtable<String,String> person;
public Hashtable<String, String> getPerson() {
return person;
}
public void setPerson(Hashtable<String, String> person) {
this.person = person;
}
}
3.最后在 resources 中,加入配置文件,文件名为 user.yaml:
user:
person:
AAA: 1
BBB: 2
在 resources 中,加入配置文件,文件名为 user.properties:
user.person.AAA=1
user.person.BBB=2
测试程序就不写了,大家请自行测试。