1. 程式人生 > >Spring Boot 配置優先順序順序

Spring Boot 配置優先順序順序

一般在一個專案中,總是會有好多個環境。比如:

開發環境 -> 測試環境 -> 預釋出環境【驗證環境】 -> 生產環境

每個環境上的配置檔案總是不一樣的,甚至開發環境中每個開發者的環境可能也會有一點不同,配置讀取可是一個讓人有點傷腦筋的問題。

Spring Boot提供了一種優先順序配置讀取的機制來幫助我們從這種困境中走出來。

常規情況下,我們都知道Spring Boot的配置會從application.properties中讀取。實際上,從resource目錄下的application.properties檔案讀取是Spring Boot配置鏈中的一環而已。

外部化的配置

在應用中管理配置並不是一個容易的任務,尤其是在應用需要部署到多個環境中時。通常會需要為每個環境提供一個對應的屬性檔案,用來配置各自的資料庫連線資訊、伺服器資訊和第三方服務賬號等。通常的應用部署會包含開發、測試和生產等若干個環境。不同的環境之間的配置存在覆蓋關係。測試環境中的配置會覆蓋開發環境,而生產環境中的配置會覆蓋測試環境。Spring 框架本身提供了多種的方式來管理配置屬性檔案。Spring 3.1 之前可以使用 PropertyPlaceholderConfigurer。
Spring 3.1 引入了新的環境(Environment)和概要資訊(Profile)API,是一種更加靈活的處理不同環境和配置檔案的方式。不過 Spring 這些配置管理方式的問題在於選擇太多,讓開發人員無所適從。Spring Boot 提供了一種統一的方式來管理應用的配置,允許開發人員使用屬性檔案、YAML 檔案、環境變數和命令列引數來定義優先順序不同的配置值。

Spring Boot 所提供的配置優先順序順序比較複雜。按照優先順序從高到低的順序,具體的列表如下所示。

  1. 命令列引數。
  2. 通過 System.getProperties() 獲取的 Java 系統引數。
  3. 作業系統環境變數。
  4. 從 java:comp/env 得到的 JNDI 屬性。
  5. 通過 RandomValuePropertySource 生成的“random.*”屬性。
  6. 應用 Jar 檔案之外的屬性檔案。(通過spring.config.location引數)
  7. 應用 Jar 檔案內部的屬性檔案。
  8. 在應用配置 Java 類(包含“@Configuration”註解的 Java 類)中通過“@PropertySource”註解宣告的屬性檔案。
  9. 通過“SpringApplication.setDefaultProperties”宣告的預設屬性。

Spring Boot 的這個配置優先順序看似複雜,其實是很合理的。比如命令列引數的優先順序被設定為最高。
這樣的好處是可以在測試或生產環境中快速地修改配置引數值,而不需要重新打包和部署應用。

SpringApplication 類預設會把以“--”開頭的命令列引數轉化成應用中可以使用的配置引數,如 “--name=Alex” 會設定配置引數 “name” 的值為 “Alex”。如果不需要這個功能,可以通過 “SpringApplication.setAddCommandLineProperties(false)” 禁用解析命令列引數。

RandomValuePropertySource 可以用來生成測試所需要的各種不同型別的隨機值,從而免去了在程式碼中生成的麻煩。RandomValuePropertySource 可以生成數字和字串。數字的型別包含 int 和 long,可以限定數字的大小範圍。以“random.”作為字首的配置屬性名稱由 RandomValuePropertySource 來生成,如程式碼清單 3 所示。

清單 3. 使用 RandomValuePropertySource 生成的配置屬性
user.id=${random.value}
user.count=${random.int}
user.max=${random.long}
user.number=${random.int(100)}
user.range=${random.int[100, 1000]}

屬性檔案

屬性檔案是最常見的管理配置屬性的方式。Spring Boot 提供的 SpringApplication 類會搜尋並載入 application.properties 檔案來獲取配置屬性值。SpringApplication 類會在下面位置搜尋該檔案。

  • 當前目錄的“/config”子目錄。
  • 當前目錄。
  • classpath 中的“/config”包。
  • classpath

上面的順序也表示了該位置上包含的屬性檔案的優先順序。優先順序按照從高到低的順序排列。可以通過“spring.config.name”配置屬性來指定不同的屬性檔名稱。也可以通過“spring.config.location”來新增額外的屬性檔案的搜尋路徑。如果應用中包含多個 profile,可以為每個 profile 定義各自的屬性檔案,按照“application-{profile}”來命名。

對於配置屬性,可以在程式碼中通過“@Value”來使用,如程式碼清單 4 所示。

清單 4. 通過“@Value”來使用配置屬性
複製程式碼
@RestController
@EnableAutoConfiguration
public class Application {
 @Value("${name}")
 private String name;
 @RequestMapping("/")
 String home() {
 return String.format("Hello %s!", name);
 }
}
複製程式碼

程式碼清單 4 中,變數 name 的值來自配置屬性中的“name”屬性。

YAML

相對於屬性檔案來說,YAML 是一個更好的配置檔案格式。YAML 在 Ruby on Rails 中得到了很好的應用。SpringApplication 類也提供了對 YAML 配置檔案的支援,只需要新增對 SnakeYAML 的依賴即可。程式碼清單 5 給出了 application.yml 檔案的示例。

清單 5. 使用 YAML 表示的配置屬性
複製程式碼
spring:
 profiles: development
db:
 url: jdbc:hsqldb:file:testdb
 username: sa
 password:
---
spring:
 profiles: test
db:
 url: jdbc:mysql://localhost/test
 username: test
 password: test
複製程式碼

程式碼清單 5 中的 YAML 檔案同時給出了 development 和 test 兩個不同的 profile 的配置資訊,這也是 YAML 檔案相對於屬性檔案的優勢之一。
除了使用“@Value”註解繫結配置屬性值之外,還可以使用更加靈活的方式。
程式碼清單 6 給出的是使用程式碼清單 5 中的 YAML 檔案的 Java 類。
通過“@ConfigurationProperties(prefix="db")”註解,配置屬性中以“db”為字首的屬性值會被自動繫結到 Java 類中同名的域上,如 url 域的值會對應屬性“db.url”的值。
只需要在應用的配置類中新增“@EnableConfigurationProperties”註解就可以啟用該自動繫結功能。

清單 6. 使用 YAML 檔案的 Java 類
複製程式碼
@Component
@ConfigurationProperties(prefix="db")
public class DBSettings {
 private String url;
 private String username;
 private String password;
}
複製程式碼

http://www.ibm.com/developerworks/cn/java/j-lo-spring-boot/index.html

 

 

這意味著,如果Spring Boot在優先順序更高的位置找到了配置,那麼它就會無視優先順序低的配置

比如,我在application.properties目錄中,寫入本地的MySQL的配置:

db.jdbc.driver=com.mysql.jdbc.Driver
db.jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8
db.jdbc.username=username
db.jdbc.password=password

在自己專案除錯的階段,專案總是會使用本地的MySQL資料庫。而一旦打包之後,在外部宣告一個test_evn.properties.

啟動Jar包的時候, 指定一個外部配置檔案:

java -jar demo.jar --spring.config.location=/path/test_evn.properties

這樣一來,我們在開發者的機器上總是使用自己的配置,而一到對應的環境,就會使用高階的位置所做的配置。

在程式碼中讀取這些配置也是非常方便的,在程式碼的邏輯中,其實是無需去關心這個配置是從什麼地方來的,只用關注能獲取什麼配置就夠了。

複製程式碼
public class ApplicationConfigure {

    @Value("${db.jdbc.driver}")
    private String jdbcDriver;
    @Value("${db.jdbc.url}")
    private String jdbcUrl;
    @Value("${db.jdbc.username}")
    private String jdbcUsername;
    @Value("${db.jdbc.password}")
    private String jdbcPassword;
    
    // mysql config class
    // ..... 
    
}
複製程式碼

 

有時候我們在專案啟動的時候,總是需要先啟動一些初始化的類,以前比較常見的做法是寫再static塊中,Spring Boot提供了一個CommandLineRunner介面,實現這個介面的類總是會被優先啟動,並優先執行CommandLineRunner介面中提供的run()方法。

複製程式碼
public class ApplicationConfigure implements CommandLineRunner  {

    @Value("${db.jdbc.driver}")
    private String jdbcDriver;
    @Value("${db.jdbc.url}")
    private String jdbcUrl;
    @Value("${db.jdbc.username}")
    private String jdbcUsername;
    @Value("${db.jdbc.password}")
    private String jdbcPassword;
    
    // mysql config class
    // ..... 
    @Override
    public void run(String... strings) throws Exception {
        // 預先載入的一些方法,類,屬性。
    }
}
複製程式碼

 

如果有多個CommandLineRunner介面實現類,那麼可以通過註解@Order來規定所有實現類的執行順序。

通過這一系列API的幫助,Spring Boot讓環境配置變得輕鬆很多。

http://www.cnblogs.com/whthomas/p/5270917.html

http://www.ibm.com/developerworks/cn/java/j-lo-spring-boot/index.html

Tomcat 
Tomcat為Spring Boot的預設容器,下面是幾個常用配置:

複製程式碼
# tomcat最大執行緒數,預設為200
server.tomcat.max-threads=800
# tomcat的URI編碼
server.tomcat.uri-encoding=UTF-8
# 存放Tomcat的日誌、Dump等檔案的臨時資料夾,預設為系統的tmp資料夾(如:C:\Users\Shanhy\AppData\Local\Temp)
server.tomcat.basedir=H:/springboot-tomcat-tmp
# 開啟Tomcat的Access日誌,並可以設定日誌格式的方法:
#server.tomcat.access-log-enabled=true
#server.tomcat.access-log-pattern=
# accesslog目錄,預設在basedir/logs
#server.tomcat.accesslog.directory=
# 日誌檔案目錄
logging.path=H:/springboot-tomcat-tmp
# 日誌檔名稱,預設為spring.log
logging.file=myapp.log
複製程式碼

Jetty 

如果你要選擇Jetty,也非常簡單,就是把pom中的tomcat依賴排除,並加入Jetty容器的依賴,如下:

複製程式碼
<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
      <exclusion>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
      </exclusion>
    </exclusions>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
  </dependency>
<dependencies> 
複製程式碼

打包 

打包方法: 
CMD進入專案目錄,使用 mvn clean package 命令打包,以我的專案工程為例:

E:\spring-boot-sample>mvn clean package

可以追加引數 -Dmaven.test.skip=true (-DskipTests)跳過測試。 

打包後的檔案存放於專案下的target目錄中,如:spring-boot-sample-0.0.1-SNAPSHOT.jar 
如果pom配置的是war包,則為spring-boot-sample-0.0.1-SNAPSHOT.war

二、部署到JavaEE容器

  1. 修改啟動類,繼承 SpringBootServletInitializer 並重寫 configure 方法 複製程式碼
    public class SpringBootSampleApplication extends SpringBootServletInitializer{
    
        private static final Logger logger = LoggerFactory.getLogger(SpringBootSampleApplication.class);
    
        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
            return builder.sources(this.getClass());
        }
    
    }
    複製程式碼
  1. 修改pom檔案中jar 為 war
<!-- <packaging>jar</packaging> -->
<packaging>war</packaging>
  1. 修改pom,排除tomcat外掛

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>

<exclusions>

<exclusion>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-tomcat</artifactId>

</exclusion>

</exclusions>

</dependency>

  1. 打包部署到容器 
    使用命令 mvn clean package 打包後,同一般J2EE專案一樣部署到web容器。

三、使用Profile區分環境

spring boot 可以在 “配置檔案”、“Java程式碼類”、“日誌配置” 中來配置profile區分不同環境執行不同的結果

1、配置檔案 
使用配置檔案application.yml 和 application.properties 有所區別 
以application.properties 為例,通過檔名來區分環境 application-{profile}.properties 
application.properties

app.name=MyApp
server.port=8080
spring.profiles.active=dev

application-dev.properties

server.port=8081

application-stg.properties

server.port=8082

在啟動程式的時候通過新增 –spring.profiles.active={profile} 來指定具體使用的配置 

例如我們執行 java -jar demo.jar spring.profiles.active=dev 那麼上面3個檔案中的內容將被如何應用? 
Spring Boot 會先載入預設的配置檔案,然後使用具體指定的profile中的配置去覆蓋預設配置。

app.name 只存在於預設配置檔案 application.properties 中,因為指定環境中不存在同樣的配置,所以該值不會被覆蓋 
server.port 預設為8080,但是我們指定了環境後,將會被覆蓋。如果指定stg環境,server.port 則為 8082 
spring.profiles.active 預設指定dev環境,如果我們在執行時指定 –spring.profiles.active=stg 那麼將應用stg環境,最終 server.port 的值為8082

2、Java類中@Profile註解 
下面2個不同的類實現了同一個介面,@Profile註解指定了具體環境

複製程式碼
// 介面定義
public interface SendMessage {

    // 傳送簡訊方法定義
    public void send();

}
複製程式碼
 
 
 
  複製程式碼
  
 
// Dev 環境實現類
@Component
@Profile("dev")
public class DevSendMessage implements SendMessage {

    @Override
    public void send() {
        System.out.println(">>>>>>>>Dev Send()<<<<<<<<");
    }

}
複製程式碼

 

複製程式碼
// Stg環境實現類
@Component
@Profile("stg")
public class StgSendMessage implements SendMessage {

    @Override
    public void send() {
        System.out.println(">>>>>>>>Stg Send()<<<<<<<<");
    }

}
複製程式碼 複製程式碼
// 啟動類
@SpringBootApplication
public class ProfiledemoApplication {

    @Value("${app.name}")
    private String name;

    @Autowired
    private SendMessage sendMessage;

    @PostConstruct
    public void init(){
        sendMessage.send();// 會根據profile指定的環境例項化對應的類
    }

}
複製程式碼

3、logback-spring.xml也支援有節點來支援區分

複製程式碼
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml" />
    <logger name="org.springframework.web" level="INFO"/>

    <springProfile name="default">
        <logger name="org.springboot.sample" level="TRACE" />
    </springProfile>

    <springProfile name="dev">
        <logger name="org.springboot.sample" level="DEBUG" />
    </springProfile>

    <springProfile name="staging">
        <logger name="org.springboot.sample" level="INFO" />
    </springProfile>

</configuration>
複製程式碼

再說一遍檔名不要用logback.xml 請使用logback-spring.xml

四、指定外部的配置檔案

有些系統,關於一些資料庫或其他第三方賬戶等資訊,由於安全問題,其配置並不會提前配置在專案中暴露給開發人員。 
對於這種情況,我們在執行程式的時候,可以通過引數指定一個外部配置檔案。 
以 demo.jar 為例,方法如下:

java -jar demo.jar --spring.config.location=/opt/config/application.properties

其中檔名隨便定義,無固定要求。

五、建立一個Linux 應用的sh指令碼

下面幾個指令碼僅供參考,請根據自己需要做調整 
start.sh

複製程式碼
#!/bin/sh

rm -f tpid

nohup java -jar /data/app/myapp.jar --spring.profiles.active=stg > /dev/null 2>&1 &

echo $! > tpid
複製程式碼

 

stop.sh

tpid=`cat tpid | awk '{print $1}'`

tpid=`ps -aef | grep $tpid | awk '{print $2}' |grep $tpid`
if [ ${tpid} ]; then
   kill -9 $tpid
fi

check.sh

複製程式碼
tpid=`cat tpid | awk '{print $1}'`
tpid=`ps -aef | grep $tpid | awk '{print $2}' |grep $tpid`
if [ ${tpid} ]; then
    echo App is running.
else
    echo App is NOT running.
fi
複製程式碼

kill.sh

#!/bin/sh
# kill -9 `ps -ef|grep 專案名稱|awk '{print $2}'`
kill -9 `ps -ef|grep demo|awk '{print $2}'`