public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(@Nullable 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;
}
}
}
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:blog.yml")
@Component
@ConfigurationProperties(prefix = "blog")
@Data
public class Blog {
private Integer id;
private String name;
}
blog.yml:
blog:
id: 123
name: tiger
单测:
public class LogTest extends BaseTest{
@Autowired
Blog blog;
@Test
public void test(){
System.out.println(blog.getId());
}
}
或者:
@SpringBootApplication
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:blog.yml")
public class YamlPropertysourceApplication {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(YamlPropertysourceApplication.class, args);
ConfigurableEnvironment env = ctx.getEnvironment();
env.getPropertySources().forEach(ps -> System.out.println(ps.getName() + " : " + ps.getClass()));
System.out.println("Value of `blog.id` = " + env.getProperty("blog.id"));
}
}