玩轉Spring Boot 自訂配置、匯入XML配置與外部化配置

來源:互聯網
上載者:User

標籤:內聯   1.4   預設的配置   files   href   print   注入   dep   plain   

玩轉Spring Boot 自訂配置、匯入XML配置與外部化配置
      在這裡我會全面介紹在Spring Boot裡面如何自訂配置,更改Spring Boot預設的配置,以及介紹各配置的優先順序順序。Spring Boot使用一個全域的設定檔application.properties,Spring Boot 支援使用YAML語言的設定檔,YAML是以資料位元中心的語言,所以使用application.yml作為全域配置也是同樣的效果,如果使用YAML替代properties注意寫法,冒號後面要加個空格,否則會解析不出來。而且在Spring Boot裡面配置名稱支援多種方式,例如:server.ssl.key-store,可以寫成:server.ssl.keyStore都是可以的。下面具體詳細介紹。
1.引用XML檔案配置      在實際項目中有的情況需要使用到XML設定檔,或者是你還不習慣用Java 配置的方式,那麼你可以通過在入口啟動類上加上@ImportResource(value = { "路徑" })或者使用@ImportResource(locations= { "路徑" }),一樣的效果,多個XML檔案的話你可以用逗號“,”分隔,就這樣輕而易舉引用XML配置。
2.引入多個@Configuration 配置類      在實際項目中可能不會把所有的配置都放在一個配置類(用@Configuration註解的類)中,可能會分開配置。這時可以用@Import註解引用。
3.引用自訂properties      Spring Boot使用全域配置(application.properties)提供了很多的預設的配置屬性。在開發的時候,大多數會用到自訂的一些配置屬性,例如:指定上傳檔案儲存的路徑,定義:file.upload.stor-path=E:/test/,Spring Boot 提供了@Value註解擷取properties中的屬性,還提供了基於型別安全的配置方式,通過@ConfigurationProperties將properties屬性注入到一個Bean中,在1.4以上版本官方不建議使用@ConfigurationProperties來指定properties檔案位置。接下來請看執行個體:      在pom.xml中加入以下依賴:[html] view plain copy print?
  1. <dependency>    
  2.           <groupId>org.springframework.boot</groupId>    
  3.           <artifactId>spring-boot-configuration-processor</artifactId>    
  4.           <optional>true</optional>    
  5. </dependency>   
<dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-configuration-processor</artifactId>            <optional>true</optional>  </dependency> 

第一種:     (1) 在src/main/resources下建立application.properties檔案並加入以下代碼:[plain] view plain copy print?
  1. file.upload.stor-path=E:/test/  
file.upload.stor-path=E:/test/
      (2)直接使用@Value註解方式,具體代碼如下:[java] view plain copy print?
  1. package com.chengli.springboot.helloworld;  
  2.   
  3. import org.springframework.beans.factory.annotation.Value;  
  4. import org.springframework.boot.SpringApplication;  
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.bind.annotation.RestController;  
  8.   
  9. @RestController  
  10. @SpringBootApplication  
  11. public class SampleController {  
  12.     @Value(value = "${file.upload.stor-path}")  
  13.     private String storPath;  
  14.   
  15.     @RequestMapping("/")  
  16.     String home() {  
  17.         return "Hello World! file.upload.stor-path為:" + storPath;  
  18.     }  
  19.   
  20.     public static void main(String[] args) throws Exception {  
  21.         SpringApplication springApplication = new SpringApplication(SampleController.class);  
  22.         springApplication.run(args);  
  23.     }  
  24. }  
package com.chengli.springboot.helloworld;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@[email protected] class SampleController {    @Value(value = "${file.upload.stor-path}")    private String storPath;    @RequestMapping("/")    String home() {        return "Hello World! file.upload.stor-path為:" + storPath;    }    public static void main(String[] args) throws Exception {        SpringApplication springApplication = new SpringApplication(SampleController.class);        springApplication.run(args);    }}
第二種:      屬性配置放在application.properties檔案中,使用@ConfigurationProperties將配置屬性注入到Bean中,代碼如下:      (1)定義FileUploadProperties類[java] view plain copy print?
  1. package com.chengli.springboot.helloworld;  
  2.   
  3. import org.springframework.boot.context.properties.ConfigurationProperties;  
  4. import org.springframework.stereotype.Component;  
  5.   
  6. @Component  
  7. @ConfigurationProperties(prefix = "file.upload")  
  8. public class FileUploadProperties {  
  9.     private String storPath;  
  10.   
  11.     public String getStorPath() {  
  12.         return storPath;  
  13.     }  
  14.   
  15.     public void setStorPath(String storPath) {  
  16.         this.storPath = storPath;  
  17.     }  
  18. }  
package com.chengli.springboot.helloworld;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;@[email protected](prefix = "file.upload")public class FileUploadProperties {    private String storPath;    public String getStorPath() {        return storPath;    }    public void setStorPath(String storPath) {        this.storPath = storPath;    }}
      (2)入口啟動類代碼如下:[java] view plain copy print?
  1. package com.chengli.springboot.helloworld;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.boot.SpringApplication;  
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.bind.annotation.RestController;  
  8.   
  9. @RestController  
  10. @SpringBootApplication  
  11. public class SampleController {  
  12.     @Autowired  
  13.     private FileUploadProperties fileUploadProperties;  
  14.   
  15.     @RequestMapping("/")  
  16.     String home() {  
  17.         return "Hello World! file.upload.stor-path為:" + fileUploadProperties.getStorPath();  
  18.     }  
  19.   
  20.     public static void main(String[] args) throws Exception {  
  21.         SpringApplication springApplication = new SpringApplication(SampleController.class);  
  22.         springApplication.run(args);  
  23.     }  
  24. }  
package com.chengli.springboot.helloworld;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@[email protected] class SampleController {    @Autowired    private FileUploadProperties fileUploadProperties;    @RequestMapping("/")    String home() {        return "Hello World! file.upload.stor-path為:" + fileUploadProperties.getStorPath();    }    public static void main(String[] args) throws Exception {        SpringApplication springApplication = new SpringApplication(SampleController.class);        springApplication.run(args);    }}
      注意:這裡我對FileUploadProperties使用了@Component註解,如果沒有使用@Component註解,則需要在入口啟動類上加上@EnableConfigurationProperties註解。Spring Boot 在properties檔案中支援使用SpEL運算式,可以進行校正(校正註解使用的是javax.validation)等操作。
例如以下:(1)隨機數:          test.int.random=${random.int}(2)數組注入          test.int.random[0]=${random.int}          test.int.random[1]=${random.int}(3)校正         @NotNull
         private String storPath;

4.外部化配置(配置方式與優先順序)      Spring Boot 允許外化配置,Spring Boot使用了一個特別的PropertySource次序來允許對值進行覆蓋,覆蓋的優先順序順序如下:  (1)Devtools全域設定主目錄(~ /.spring-boot-devtools.properties 為活躍的)。  (2)@TestPropertySource註解在Test。  (3)@SpringBootTest#properties 註解在Test。  (4)命令列參數。  (5)從SPRING_APPLICATION_JSON屬性(內聯JSON嵌入在一個環境變數或系統屬性)。  (6)ServletConfig init參數。  (7)ServletContext init參數。  (8)JNDI屬性java:comp/env。  (9)Java系統屬性(System.getProperties())。  (10)作業系統環境變數。  (11)RandomValuePropertySource配置的random.*屬性值  (12)打包在jar以外的application-{profile}.properties或application.yml設定檔  (13)打包在jar以內的application-{profile}.properties或application.yml設定檔  (14)打包在jar以外的application.properties或application.yml設定檔  (15)打包在jar以內的application.properties或application.yml設定檔  (16)@configuration註解類上的@PropertySource。  (17)預設的屬性(使用SpringApplication.setDefaultProperties指定)。
a) 通過命令列來修改預設參數,例如:     啟動命令:java -jar *.jar --name="chengli"     以上的意思是,將name值修改為:chenglib) 通過命令列來設定載入properties 例如:     java -jar *.jar --spring.profiles.active=dev     這裡如果不瞭解profile的話,後面的文章中會介紹到。
5.application.properties檔案按優先順序,優先順序高的會覆蓋優先順序低的   優先順序順序如下:  (1)目前的目錄下的一個/config子目錄  (2)目前的目錄  (3)一個classpath下的/config包  (4)classpath根目錄

有興趣的朋友可以加群探討相互學習:

Spring Boot QQ交流群:599546061

玩轉Spring Boot 自訂配置、匯入XML配置與外部化配置

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.