1. 程式人生 > 實用技巧 >springboot學習筆記(3)

springboot學習筆記(3)

springboot引入外部配置檔案

SpringBoot 的預設配置檔案是 application.yml 或者 application.properties,接下來介紹引入其他的 properties 檔案 或者 yml 檔案的做法。

1、properties 檔案

properties 檔案引入較為簡單,跟 Spring 一樣。在配置類上使用 @PropertySource 註解引入,在其他地方使用 @Value 註解讀取。

2、yml 檔案

先從 SpringBoot 的預設配置檔案 application.yml 檔案開始,application.yml 的檔案內容,是可以通過 @Value 的方式讀取到的,比如 @Value("${server.port}") 這樣。究其原因的話,應該是 SpringBoot 底層把 ApplicationContext 註冊進 PropertySourcesPlaceholderConfigurer 所導致的

那麼我們自定義的 yml 檔案要怎麼引入

1     @Bean
2     public PropertySourcesPlaceholderConfigurer properties() {
3         PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
4         YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
5         yaml.setResources(new
ClassPathResource("my.yml")); 6 configurer.setProperties(yaml.getObject()); 7 return configurer; 8 }

這種方式,確實可以用,通過這種方式把 yml 檔案載入到 PropertySourcesPlaceholderConfigurer 後,通過 @Value 方式讀取到屬性值。但是原來的 application.yml 中的 @Value 屬性全獲取不到了,所以不採用這種做法。

那要怎麼載入我們自定義的 yml 檔案呢?可以通過 YamlPropertiesFactoryBean 或者 YamlMapFactoryBean 類來載入

 1 @Test
 2     public void test() {
 3         YamlPropertiesFactoryBean yml = new YamlPropertiesFactoryBean();
 4         yml.setResources(new ClassPathResource("my.yml"));
 5         Properties properties = yml.getObject();
 6         Iterator<Map.Entry<Object, Object>> iterator = properties.entrySet().iterator();
 7         while (iterator.hasNext()) {
 8             Map.Entry<Object, Object> entry = iterator.next();
 9             logger.info("YamlPropertiesFactoryBean 讀取的配置檔案內容是:{}-{}", entry.getKey(), entry.getValue());
10         }
11 
12         YamlMapFactoryBean yamlMapFactoryBean = new YamlMapFactoryBean();
13         yamlMapFactoryBean.setResources(new ClassPathResource("my.yml"));
14         Map<String, Object> map = yamlMapFactoryBean.getObject();
15         Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
16         while (it.hasNext()) {
17             Map.Entry<String, Object> entry = it.next();
18             logger.info("YamlPropertiesFactoryBean 讀取的配置檔案內容是:{}-{}", entry.getKey(), entry.getValue());
19         }
20     }

另外需要提及的是 SpringBoot 還提供了@ConfigurationProperties(prefix = "spring.datasource") 註解,將 yml 檔案中的屬性直接轉換成 Bean 中的屬性(前提是有 set 方法),而且屬性的匹配很寬鬆,採用 Relaxed 繫結,以 firstName 舉例(可匹配firstName、first-name、first_name、FIRST_NAME)。之後再在啟動類中使用@EnableConfigurationProperties(JavaConfig.class) 使之生效。