SpringBoot引入額外的YAML配置文件的代碼實現
背景
在SpringBoot項目中,有時需要引入除application.yml
之外的配置文件(例如在開發(fā)公共組件時)。使用@PropertySource
注解可以實現這一需求,但有一些細節(jié)點需要注意,在此記錄。
代碼實現
假設有一份名為extra.yml
的配置文件:
# extra.yml extra: name: 張三 order: 3
對應的配置bean為:
@Data @ConfigurationProperties("extra") public class ExtraProperties { private String name; private Integer order; }
在配置類上添加相關注解,將extra.yml
配置文件添加到Spring環(huán)境中:
@Configuration @EnableConfigurationProperties(ExtraProperties.class) @PropertySource( // 配置文件路徑 value = "classpath:/extra.yml", // 當配置文件不存在時,是忽略還是報錯 ignoreResourceNotFound = true, // 配置文件編碼 encoding = "UTF-8", // 配置文件加載工廠 factory = YamlPropertySourceFactory.class) public class ExtraConfig { }
由于@PropertySource
默認支持的是.properties
格式的配置文件,而我們一般使用的是YAML格式的,因此這里自定義了配置文件加載工廠,支持YAML,并解決ignoreResourceNotFound
不生效的問題:
/** * YAML配置文件加載工廠 */ public class YamlPropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { try { return new YamlPropertySourceLoader() .load(resource.getResource().getFilename(), resource.getResource()) .get(0); } catch (IllegalStateException e) { // 如果YAML配置文件不存在,希望能忽略該文件,而不是引發(fā)異常導致Spring容器啟動失敗 // 需要往外拋FileNotFoundException,Spring捕捉到后會忽略該異常(當 ignoreResourceNotFound = true 時) if (e.getCause() instanceof FileNotFoundException) { throw (FileNotFoundException) e.getCause(); } else { throw e; } } } }
這樣,ExtraProperties配置bean里的屬性值, 就與extra.yml里的配置值綁定在一起了。
補充說明
標準配置文件application.yml的生效優(yōu)先級高于額外引入的配置文件。如果application.yml中指定了相同的配置項,則它會覆蓋extra.yml中對應的配置項:
# application.yml,會覆蓋extra.yml中的相同配置項 extra: name: 李四 order: 4
當然,如果使用了環(huán)境配置文件application-{profile}.yml,則它的生效優(yōu)先級又會高于application.yml。
另外,@PropertySource支持引入多個配置文件。例如,在引入extra.yml的同時,引入對應的環(huán)境配置文件extra-{profile}.yml:
@Configuration @EnableConfigurationProperties(ExtraProperties.class) @PropertySource( value = {"classpath:/extra.yml", "classpath:/extra-${spring.profiles.active}.yml"}, ignoreResourceNotFound = true, encoding = "UTF-8", // 配置文件加載工廠 factory = YamlPropertySourceFactory.class) public class ExtraConfig { }
這里,Spring會將占位符${spring.profiles.active}解析為對應的值。例如,在application.yml中指定spring.profiles.active=dev,那么配置文件extra-dev.yml會被引入(如有),它的生效優(yōu)先級高于extra.yml,但低于application.yml。
# extra-dev.yml,會覆蓋extra.yml中的相同配置項 extra: name: 王五 order: 5
總結
- @PropertySource用于引入額外的配置文件。
- 通過自定義配置文件加載工廠,可支持YAML文件解析,并支持ignoreResourceNotFound。
- 配置文件生效的優(yōu)先級順序為:application-{profile}.yml>application.yml>extra-{profile}.yml>extra.yml。
以上就是SpringBoot引入額外的YAML配置文件的代碼實現的詳細內容,更多關于SpringBoot引入額外YAML文件的資料請關注腳本之家其它相關文章!