一、读取properties文件
在类已经注入为bean的情况下,使用@PropertySource配置文件路径:
@PropertySource("classpath:demo.properties")
之后使用注解 @Value与属性绑定即可
@Value("${test}")
private String test;
demo.properties:
test=test read properties file
二、读取yml文件
可以在启动类添加下面代码:
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
//yaml.setResources(new FileSystemResource("/dir/application.yml"));//File引入
yaml.setResources(new ClassPathResource("demo.yml"));//class引入
configurer.setProperties(yaml.getObject());
return configurer;
}
之后取值与上面一样,使用@Value与属性绑定即可。
- 如果需要引入多个配置文件:
yaml.setResources(new ClassPathResource("demo1.yml"), new ClassPathResource("demo2.yml"));