天天看點

Spring Boot 系列(三)屬性配置&自定義屬性配置

在使用spring boot過程中,可以發現項目中隻需要極少的配置就能完成相應的功能,這歸功于spring boot中的子產品化配置,在pom.xml中依賴的每個Starter都有預設配置,而這些預設配置足以滿足正常的功能開發。

如果需要修改自定義修改預設配置,spring boot 提供了很簡便的方法,隻需要在application.properties 中添加修改相應的配置。(spring boot啟動的時候會讀取application.properties這份預設配置)

一、修改預設配置

例1、spring boot 開發web應用的時候,預設tomcat的啟動端口為8080,如果需要修改預設的端口,則需要在application.properties 添加以下記錄:

server.port=8888
           
重新開機項目,啟動日志可以看到:Tomcat started on port(s): 8888 (http) 啟動端口為8888,浏覽器中通路 http://localhost:8888 能正常通路。

例2、spring boot 開發中的資料庫連接配接資訊配置(這裡使用com.alibaba 的 druid), 在application.properties 添加以下記錄:

druid.url=jdbc:mysql://192.168.0.20:3306/test
druid.driver-class=com.mysql.jdbc.Driver
druid.username=root
druid.password=123456
druid.initial-size=1
druid.min-idle=1
druid.max-active=20
druid.test-on-borrow=true
           
以上兩個例子,說明了如需修改starter子產品中的預設配置,隻需要在在application.properties 添加需要修改的配置即可。
附: application.properties 全部配置項,點選檢視Spring Boot 所有配置說明

二、自定義屬性配置

在application.properties中除了可以修改預設配置,我們還可以在這配置自定義的屬性,并在實體bean中加載出來。

1、在application.properties中添加自定義屬性配置

com.sam.name=sam
com.sam.age=11
com.sam.desc=magical sam
           

2、編寫Bean類,加載屬性

Sam類需要添加@Component注解,讓spring在啟動的時候掃描到該類,并添加到spring容器中。
第一種:使用spring支援的@Value()加載
package com.sam.demo.conf;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author sam
 * @since 2017/7/15
 */
@Component
public class Sam {

    //擷取application.properties的屬性
    @Value("${com.sam.name}")
    private String name;

    @Value("${com.sam.age}")
    private int age;

    @Value("${com.sam.desc}")
    private String desc;
    
    //getter & setter
}

           
第二種:使用@ConfigurationProperties(prefix="") 設定字首,屬性上不需要添加注解。
package com.sam.demo.conf;

import org.springframework.stereotype.Component;

/**
 * @author sam
 * @since 2017/7/15
 */
@Component
@ConfigurationProperties(prefix = "com.sam")
public class Sam {

    private String name;

    private int age;

    private String desc;

    //getter & setter
}

           

3、在controller中注入并使用Sam這個Bean。

package com.sam.demo.controller;

import com.sam.demo.conf.Sam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author sam
 * @since 2017/7/14
 */
@RestController
public class IndexController {

    @Autowired
    private Sam sam;

    @RequestMapping("/index")
    public String index() {
        System.out.println(sam.getName() + " " + sam.getAge() + " " + sam.getDesc());
        return "index";
    }

}

           
浏覽器通路:http://localhost:8080/index ,控制台正常列印出sam的内容。

三、application.properties 屬性配置詳解

1、參數引用與random随機數方法的使用

在application.properties内可以直接通過${}引用其他屬性的值,如下:
com.sam.name=sam
com.sam.age=11
com.sam.desc=${name} is ${age} years old. 

           
在application.properties中如果需要擷取随機數,可以通過${random},如下:
#擷取随機字元串
com.sam.randomValue=${random.value}

#擷取随機字元串:${random.value}
#擷取随機int:${random.int}
#擷取10以内的随機數:${random.int(10)}
#擷取10-20的随機數:${random.int[10,20]}
#擷取随機long:${random.long}
#擷取随機uuid:${random.uuid}
           

2、多環境配置

實際開發中可能會有不同的環境,有開發環境、測試環境、生成環境。對于每個環境相關配置都可能有所不同,如:資料庫資訊、端口配置、本地路徑配置等。
如果每次切換不同環境都需要修改application.properties,那麼操作是十分繁瑣的。在spring boot中提供了多環境配置,使得我們切換環境變得簡便。

在application.properties同目錄下建立一下三個檔案:

application-dev.properties      //開發環境的配置檔案
application-test.properties     //測試環境的配置檔案
application-prod.properties     //生産環境的配置檔案
           

上面三個檔案分别對應了 開發、測試、生産 的配置内容,接下來就是應該怎麼選擇性引用這些配置了。

在application.properties添加:

spring.profiles.active=dev
#引用測試的配置檔案
#spring.profiles.active=test
#引用生産的配置檔案
#spring.profiles.active=prod
           
添加spring.profiles.active=dev後啟動應用,會發現引用了dev的這份配置資訊。
可以看出上面三個配置檔案符合 application-{profile}.properties 格式,而在application.properties添加的 spring.profiles.active=dev 中的dev正是上面配置檔案中的 profile。根據具體環境進行切換即刻。
用指令運作jar包啟動應用的時候,可以指定相應的配置.
java -jar demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev
           
附:配置方式和優先級
這些方式優先級如下:
a. 指令行參數
b. 來自java:comp/env的JNDI屬性
c. Java系統屬性(System.getProperties())
d. 作業系統環境變量
e. RandomValuePropertySource配置的random.*屬性值
f. jar外部的application-{profile}.properties或application.yml(帶spring.profile)配置檔案
g. jar内部的application-{profile}.properties或application.yml(帶spring.profile)配置檔案
h. jar外部的application.properties或application.yml(不帶spring.profile)配置檔案
i. jar内部的application.properties或application.yml(不帶spring.profile)配置檔案
j. @Configuration注解類上的@PropertySource
k. 通過SpringApplication.setDefaultProperties指定的預設屬性
           

注:指令行參數這種jar包指定參數啟動應用的方式,可能是不安全的,我們可以設定禁止這種方式啟動應用,如下:

springApplication.setAddCommandLineProperties(false);
package com.sam.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
//        SpringApplication.run(DemoApplication.class, args);
        SpringApplication springApplication = new SpringApplication(DemoApplication.class);
        //禁止指令行設定參數
        springApplication.setAddCommandLineProperties(false);
        springApplication.run(args);
    }
}

           

補充:

在spring boot 中配置除了支援 application.properties,還支援application.yml的配置方式,如下:
建立application.yml代替application.properties
server:
  port: 9999

com:
  sam:
    name: sam
    age: 11
    desc: magical sam
           
注意:port: 9999 中間是有空格的,yml文法請參考:yml配置檔案用法
版權聲明:本文為部落客原創文章,轉載請注明出處。