spring boot 多環境配置讀取屬性檔案
阿新 • • 發佈:2019-01-02
相信很多人選擇Spring Boot主要是考慮到它既能兼顧Spring的強大功能,還能實現快速開發的便捷。我們在Spring Boot使用過程中,最直觀的感受就是沒有了原來自己整合Spring應用時繁多的XML配置內容,替代它的是在pom.xml中引入模組化的Starter POMs,其中各個模組都有自己的預設配置,所以如果不是特殊應用場景,就只需要在application.properties中完成一些屬性配置就能開啟各模組的應用。
在之前的各篇文章中都有提及關於application.properties的使用,主要用來配置資料庫連線、日誌相關配置等。除了這些配置內容之外,本文將具體介紹一些在application.properties配置中的其他特性和使用方法。
自定義屬性與載入
中就已經有介紹過了,這裡也當做溫故下吧,當然重點還是之後的多環境配置檔案。
我們在使用Spring Boot的時候,通常也需要定義一些自己使用的屬性,我們可以如下方式直接定義:
在src/main/resources/application.properties:加入:
1 2 3 |
#自定義屬性.
com.kfit.blog.name= Angel
com.kfit.blog.title=Spring Boot教程
|
然後通過@Value("${屬性名}")註解來載入對應的配置屬性,具體如下:
(以下這種方式已經過時了,不推薦使用,但能正常執行的)。
1 2 3 4 5 6 7 8 9 10 11 |
@Component
public class BlogProperties {
@Value ( "${com.kfit.blog.name}" )
private String name; //部落格作者
@Value ( "${com.kfit.blog.title}" )
private String title; //部落格標題
// 省略getter和setter
}
|
通過單元測試來驗證BlogProperties中的屬性是否已經根據配置檔案載入了。
引入單元測試依賴:
1 2 3 4 5 6 |
<!-- spring boot 單元測試. -->
< dependency >
< groupId >org.springframework.boot</ groupId >
< artifactId >spring-boot-starter-test</ artifactId >
< scope >test</ scope >
</ dependency >
|
進行編碼進行單元測試:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.kfit;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.kfit.properties.BlogProperties;
/**
*
*
* @version v.0.1
*/
@RunWith (SpringJUnit4ClassRunner. class )
@SpringApplicationConfiguration (App. class )
public class AppTest{
@Autowired
private BlogProperties blogProperties;
@Test
public void testBlog() throws Exception {
System.out.println( "AppTest.testBlog()=" +blogProperties);
Assert.assertEquals( |