1、my.yml
init:
name: kk
age: 89
2、自己实现 YamlPropertySourceFactory
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
Properties propertiesFromYaml = loadYamlIntoProperties(resource);
String sourceName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
} catch (IllegalStateException e) {
// for ignoreResourceNotFound
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException) throw (FileNotFoundException) e.getCause();
throw e;
}
}
}
3、创建自定义配置类
@Configuration
@PropertySource(value = {"classpath:my.yml"}, factory = YamlPropertySourceFactory.class)
@ConfigurationProperties("init")
@Getter
@Setter
public class MyConfig {
private String name;
private String age;
}
4、使用
@RestController
@RequestMapping("/c")
public class ClientController {
@Resource
private MyConfig config;
@RequestMapping(path = "/1", method = RequestMethod.POST)
public Object send(@RequestBody Map param){
return config.getName();;
}
}