概要
SpringBoot 中,将yml文件的内容映射到Java对象。
代码实现
映射的Config类:DemoConfig
映射的yml文件:demo.yml
yml解析器:YamlPropertySourceFactory
@Configuration
@ConfigurationProperties(prefix = "demo")
@PropertySource(value = {"classpath:demo.yml"}, factory = YamlPropertySourceFactory.class)
@Data
public class DemoConfig {
// 关联实体映射
private Demo demo;
}
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.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String s, EncodedResource encodedResource) throws IOException {
Properties propertiesFromYaml = loadYamlIntoProperties(encodedResource);
String sourceName = s != null ? s : encodedResource.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;
}
}
}
小结
通过此方式可讲yml内容映射到Java对象,且配置内容支持Nacos的动态更新。