一塊兒來學SpringBoot | 第二篇:SpringBoot配置詳解

SpringBoot 是爲了簡化 Spring 應用的建立、運行、調試、部署等一系列問題而誕生的產物, 自動裝配的特性讓咱們能夠更好的關注業務自己而不是外部的XML配置,咱們只需遵循規範,引入相關的依賴就能夠輕易的搭建出一個WEB工程java

上一篇介紹了 SpringBoot 由來及構建方式,經過第一章的教程咱們對 SpringBoot 不在感到陌生,能夠發現 SpringBoot 雖然幹掉了 XML 但未作到 零配置,它體現出了一種 約定優於配置,也稱做按約定編程,是一種軟件設計範式,旨在減小軟件開發人員需作決定的數量,得到簡單的好處,而又不失靈活性。 通常狀況下默認的配置足夠知足平常開發所需,但在特殊的狀況下,咱們每每須要用到自定義屬性配置、自定義文件配置、多環境配置、外部命令引導等一系列功能。不用擔憂,這些 SpringBoot 都替咱們考慮好了,咱們只須要遵循它的規則配置便可git

準備前提github

爲了讓 SpringBoot 更好的生成數據,咱們須要添加以下依賴(該依賴能夠不添加,可是在 IDEA 和 STS 中不會有屬性提示,沒有提示的配置就跟你用記事本寫代碼同樣苦逼,出個問題弄哭你去),該依賴只會在編譯時調用,因此不用擔憂會對生產形成影響...web

  
    
  
  
  
   
   
            
   
   
  1. spring

  2. 數據庫

  3. 編程

  4. 瀏覽器

  5. 微信

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-configuration-processor</artifactId>    <optional>true</optional></dependency>

自定義屬性配置

在 application.properties 寫入以下配置內容app

  
    
  
  
  
   
   
            
   
   
my1.age=22my1.name=battcn

其次定義 MyProperties1.java 文件,用來映射咱們在 application.properties 中的內容,這樣一來咱們就能夠經過操做對象的方式來得到配置文件的內容了

  
    
  
  
  
   
   
            
   
   
package com.battcn.properties;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;/** * @author Levin * @since 2018/4/23 0023 */@Component@ConfigurationProperties(prefix = "my1")public class MyProperties1 {    private int age;    private String name;    // 省略 get set    @Override    public String toString() {        return "MyProperties1{" +                "age=" + age +                ", name='" + name + '\'' +                '}';    }}

接下來就是定義咱們的 PropertiesController 用來注入 MyProperties1 測試咱們編寫的代碼,值得注意的是 Spring4.x 之後,推薦使用構造函數的形式注入屬性...

  
    
  
  
  
   
   
            
   
   
import com.battcn.properties.MyProperties1;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * @author Levin * @since 2018/4/23 0023 */@RequestMapping("/properties")@RestControllerpublic class PropertiesController {    private static final Logger log = LoggerFactory.getLogger(PropertiesController.class);    private final MyProperties1 myProperties1;    @Autowired    public PropertiesController(MyProperties1 myProperties1) {        this.myProperties1 = myProperties1;    }    @GetMapping("/1")    public MyProperties1 myProperties1() {        log.info("=================================================================================================");        log.info(myProperties1.toString());        log.info("=================================================================================================");        return myProperties1;    }}

打開瀏覽器,輸入以下地址: http://localhost:8080/properties/1,觀察控制檯,監聽到以下內容則表示程序正確

  
    
  
  
  
   
   
            
   
   
2018-04-23 15:51:43.145  INFO 15352 --- [nio-8080-exec-2] c.b.controller.PropertiesController      : =================================================================================================2018-04-23 15:51:43.145  INFO 15352 --- [nio-8080-exec-2] c.b.controller.PropertiesController      : MyProperties1{age=22, name='battcn'}2018-04-23 15:51:43.145  INFO 15352 --- [nio-8080-exec-2] c.b.controller.PropertiesController      : =================================================================================================

自定義文件配置

定義一個名爲 my2.properties 的資源文件,自定義配置文件的命名不強制 application 開頭

  
    
  
  
  
   
   
            
   
   
my2.age=22my2.name=Levinmy2.email=1837307557@qq.com

其次定義 MyProperties2.java 文件,用來映射咱們在 my2.properties 中的內容。

  
    
  
  
  
   
   
            
   
   
package com.battcn.properties;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.PropertySource;import org.springframework.stereotype.Component;/** * @author Levin * @since 2018/4/23 0023 */@Component@PropertySource("classpath:my2.properties")@ConfigurationProperties(prefix = "my2")public class MyProperties2 {    private int age;    private String name;    private String email;    // 省略 get set    @Override    public String toString() {        return "MyProperties2{" +                "age=" + age +                ", name='" + name + '\'' +                ", email='" + email + '\'' +                '}';    }}

接下來在 PropertiesController 用來注入 MyProperties2 測試咱們編寫的代碼

  
    
  
  
  
   
   
            
   
   
@GetMapping("/2")public MyProperties2 myProperties2() {    log.info("=================================================================================================");    log.info(myProperties2.toString());    log.info("=================================================================================================");    return myProperties2;}

打開瀏覽器,輸入以下地址: http://localhost:8080/properties/2,觀察控制檯,監聽到以下內容則表示程序正確

  
    
  
  
  
   
   
            
   
   
2018-04-23 15:59:45.395  INFO 6232 --- [nio-8080-exec-4] c.b.controller.PropertiesController      : =================================================================================================2018-04-23 15:59:45.395  INFO 6232 --- [nio-8080-exec-4] c.b.controller.PropertiesController      : MyProperties2{age=22, name='Levin', email='1837307557@qq.com'}2018-04-23 15:59:45.395  INFO 6232 --- [nio-8080-exec-4] c.b.controller.PropertiesController      : =================================================================================================

多環境化配置

在真實的應用中,經常會有多個環境(如:開發,測試,生產等),不一樣的環境數據庫鏈接都不同,這個時候就須要用到 spring.profile.active 的強大功能了,它的格式爲 application-{profile}.properties,這裏的 application 爲前綴不能改, {profile} 是咱們本身定義的。

建立 application-dev.properties、 application-test.properties、 application-prod.properties,內容分別以下

application-dev.properties

  
    
  
  
  
   
   
            
   
   
server.servlet.context-path=/dev

application-test.properties

  
    
  
  
  
   
   
            
   
   
server.servlet.context-path=/test

application-prod.properties

  
    
  
  
  
   
   
            
   
   
server.servlet.context-path=/prod

在 application.properties 配置文件中寫入 spring.profiles.active=dev,這個時候咱們在次訪問 http://localhost:8080/properties/1 就沒用處了,由於咱們設置了它的 context-path=/dev,因此新的路徑就是 http://localhost:8080/dev/properties/1 ,由此能夠看出來咱們激活不一樣的配置讀取的屬性值是不同的

外部命令引導

前面三種方式都是基於配置文件層面的,那麼有沒有辦法外部引導呢,假設這樣的場景,咱們對已經開發完成的代碼打包發佈,期間在測試環境測試經過了,那麼便可發佈上生產,這個時候是修改 application.properties的配置方便仍是直接在命令參數配置方便呢,毫無疑問是後者更有說服力。默認狀況下, SpringApplication 會將命令行選項參數(即:--property,如--server.port=9000)添加到Environment,命令行屬性始終優先於其餘屬性源。

如何測試?

  • 進入到項目目錄,此處以我本地目錄爲主:F:/battcn-workspace/spring-boot2-learning/chapter2

  • 而後打開 cmd 程序,不會在當前目錄打開 cmd 的請自行百度,輸入: mvnpackage

  • 打包完畢後進入到:F:/battcn-workspace/spring-boot2-learning/chapter2/target 目錄中去,咱們能夠發現一個名爲chapter2-0.0.1-SNAPSHOT.jar 的包

  • 接着在打開 cmd 程序,輸入: java-jar chapter2-0.0.1-SNAPSHOT.jar--spring.profiles.active=test--my1.age=32。仔細觀察 spring.profiles.active=test、 my1.age=32 這倆配置的鍵值是否是似曾相識(不認識的請從開頭認真閱讀)

  • 最後輸入測試地址:http://localhost:8080/test/properties/1 咱們能夠發現返回的JSON變成了 {"age":32,"name":"battcn"} 表示正確

總結

  • 掌握 @ConfigurationProperties、 @PropertySource 等註解的用法及做用

  • 掌握編寫自定義配置

  • 掌握外部命令引導配置的方式

目前不少大佬都寫過關於 SpringBoot 的教程了,若有雷同,請多多包涵,本教程基於最新的 spring-boot-starter-parent2.0.1.RELEASE編寫,包括新版本的特性都會一塊兒介紹...

說點什麼

  • 我的QQ:1837307557

  • battcn開源羣(適合新手):391619659

  • 微信公衆號(歡迎調戲): battcn

我的博客:http://blog.battcn.com/

全文代碼:https://github.com/battcn/spring-boot2-learning/tree/master/chapter2


本文分享自微信公衆號 - battcn(battcn)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索