SpringBoot默認(rèn)支持properties和yml配置文件的讀取,但僅支持指定路徑下指定名稱的配置文件,當(dāng)想自定義指定路徑加載配置文件時,properties文件使用@PropertySource注解即可,但該注解并不支持加載yml!
老版本的SpringBoot可以通過@ConfigurationProperties的方式指定location
@ConfigurationProperties(locations={"classpath:myconfig.yml"})
1.0.4之后該屬性就取消了,親測可行的解決方式是,將下面這個bean加載到任何一個能被spring初始化的地方即可
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
// yaml.setResources(new ClassPathResource("myconfig.yml"));
yaml.setResources(new FileSystemResource("/data/config/myconfig.yml"));
configurer.setProperties(yaml.getObject());
return configurer;
}
接下來就可以就通過@Value注入,愉快的使用屬性啦~~~
如果使用docker部署服務(wù),指定路徑讀取配置文件,就可以把該路徑掛載到宿主機(jī),方便修改配置。