springboot學習總結系列(一):多環境下(開發環境,生產環境)使用yml 或 properties 配置文件

一、首先創建一個springboot的空項目(創建過程不再贅述,一個標準maven項目),創建完的結構如下所示,直接貼圖:



MyApplication.java文件的內容如下:

package com.test;


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

@SpringBootApplication
public class MyApplication {

	public static void main(String[] args) {
		SpringApplication.run(MyApplication.class, args);
	}
}

application.properties文件內容如下:

# 端口
server.port=8080
server.context-path=/springboot-yml-properties
pom.xml文件內容如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.test</groupId>
	<artifactId>springboot-yml-properties</artifactId>
	
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>springboot-yml-properties Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<!-- springboot 父依賴 -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.4.RELEASE</version>
	</parent>
	
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	
	<dependencies>
		
		<!-- springboot 項目熱加載支持 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
		</dependency>
		
		<!-- springboot web -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>	
		
	</dependencies>
	
	<build>
		<finalName>springboot-yml-properties</finalName>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
	
</project>

到這裏項目創建結束;

二、接下來簡單說下properties和yml文件的語法區別:

首先啓動項目,從 中我們看到已經通過properties文件將項目端口配置爲 8080,故我們在啓動項目後可以看到如下log信息:

2017-12-05 15:52:35.952  INFO 6760 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-12-05 15:52:35.959  INFO 6760 --- [  restartedMain] com.test.MyApplication                   : Started MyApplication in 3.871 seconds (JVM running for 4.331)

       接下來我們終止剛剛啓動的項目,刪除項目中的application.properties文件,在同一路徑下建立application.yml文件,並配置如下內容:

server:
  port: 8087
  context-path: /springboot-yml-properties


我們發現並沒有配置什麼新東西,和剛剛用application.properties配置文件配置的內容完全一樣,但是語法不一樣(個人認爲這樣更優雅,因爲這樣一個結構就不需要在每一行開頭都寫上server. 這樣的前綴),此時啓動項目,我們在控制檯可以看到如下信息:

2017-12-05 15:59:08.289  INFO 244 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8087 (http)
2017-12-05 15:59:08.299  INFO 244 --- [  restartedMain] com.test.MyApplication                   : Started MyApplication in 4.013 seconds (JVM running for 4.501)

看到這裏,我想您應該已經明白,剛剛的yml配置起到了和properties文件一樣的效果;

      第二部分只是想要說明使用yml配置文件會比properties配置文件在語法上會更加優雅些許(主要還看個人習慣吧),接下來我會分別使用yml和properties進行多環境下的配置說明以及參數獲取方法(springboot項目),這纔是本篇我想說的重點,算是一個總結學習吧,首先是yml文件部分

yml文件部分 start 

三、

01、首先我們都知道一個常識,那就是每個人都有自己的年齡,比如我們現在的業務需求是查詢所有年齡大於20的人的相關信息,如果我們選擇通過配置文件來配置這個值爲20的常量的話,我們該如何配置和如何從配置文件中獲取這個值呢?直接貼代碼,application.yml的內容如下(注意 “age:“ 和 “20“ 之間需要一個空格,yml的語法 ):

server:
  port: 8087
  context-path: /springboot-yml-properties

#年齡 
age: 20


ok,這樣的話我們就把這個不變的值20配置好了,那麼如何在程序中獲取到呢,我們創建TestController.java文件,代碼如下所示:

package com.test;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
	
	@Value("${age}")
	private Integer age;

	@RequestMapping("/test")
	public String test() {
		return "年齡:" + age;
	}

}
接下來我們啓動項目,訪問http://localhost:8087/springboot-yml-properties/test,可看到頁面上會顯示:年齡:20

到這裏說明,我們僅僅通過一個註解

@Value("${age}")
就在項目啓動時拿到了20這個年齡值;

02、同時我們隨着業務的擴展,可能我們不只是要查詢年齡大於20的人的相關信息,我們還需要有更多的標準,比如年齡大於20且姓王的人相關信息,這麼這個姓 王 如果我們選擇在配置文件配置的話該如何配置和在程序中讀取呢,我想看到這裏您已經知道了,直接貼代碼如下:

server:
  port: 8087
  context-path: /springboot-yml-properties

#年齡 
age: 20
#姓
lastName: 王

TestController.java文件內容修改爲:

package com.test;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
	
	@Value("${age}")
	private Integer age;
	
	@Value("${lastName}")
	private String lastName;

	@RequestMapping("/test")
	public String test() {
		return "年齡:" + age + ", 姓:" + lastName;
	}

}
啓動項目,訪問http://localhost:8087/springboot-yml-properties/test,可看到頁面上會顯示:年齡:20, 姓:王
這一步並沒有什麼特別之處,你可以看到我們用了同樣的方法拿到了相關參數;

03、這一步大家可以不看,直接看04,一個yml配置文件的靈活使用方法,基於我們打算打印 年齡:20, 姓:王 這樣一個需求:

修改配置文件如下:

server:
  port: 8087
  context-path: /springboot-yml-properties

#年齡 
age: 20
#姓
lastName: 王
content: "age: ${age}, lastName: ${lastName}"  

TestController.java文件內容修改爲:

package com.test;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
	
	@Value("${age}")
	private Integer age;
	
	@Value("${lastName}")
	private String lastName;
	
	@Value("${content}")
	private String content;

	@RequestMapping("/test")
	public String test() {
		return content;
	}

}
如您所想,訪問http://localhost:8087/springboot-yml-properties/test,可看到頁面上會顯示:age: 20, lastName: 王

這也就是在配置文件中使用當前的配置

04、到這裏大家可能意識到一個問題,那就是現在我們的查詢條件有年齡,姓兩個相關常量,我們就需要定義兩個變量並加上相應的@Value註解來爲其注入相應的值,那麼以後又有了身高,性別等這樣的參數那怎麼辦?難道要繼續在TestController.java文件中聲明成員變量並不斷的加註解

@Value
來注入嗎?答案當然是:No!

首先修改配置文件內容如下:

server:
  port: 8087
  context-path: /springboot-yml-properties

#人
person:
  age: 20
  lastName: 王
  date: 2001-03-27 

創建一個java文件PersonPropertiesInfo.java,代碼如下:

package com.test;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "person")
public class PersonPropertiesInfo {

	private Integer age;

	private String lastName;

	private String date;

	//set get...忽略,一定要有set方法

}

TestController.java文件內容修改爲:
package com.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
	
	@Autowired
	private PersonPropertiesInfo personPropertiesInfo;

	@RequestMapping("/test")
	public String test() {
		return "年齡:" + personPropertiesInfo.getAge() +
				" 姓:" + personPropertiesInfo.getLastName() +
				" 出生日期:" + personPropertiesInfo.getDate();
	}

}
訪問http://localhost:8087/springboot-yml-properties/test,可看到頁面上會顯示:年齡:20 姓:王 出生日期:2001-03-27

到這裏我們可以看到 我們不再需要在每個屬性上加@Value註解,只需加一個前綴即可,很方便;

但是這裏需要爲每個成員生成set get方法,因此我在這裏提供另一種方式(瞭解即可,個人不推薦使用),那就是每個成員變量上繼續加@Value註解,您看到這裏可能會說如果這樣的話前面何必說那麼多呢,我只能說這樣的唯一好處就是不需要set方法,只需要get方法供您獲取其值即可:

此種狀態下,PersonPropertiesInfo.java文件內容如下:

package com.test;

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

@Component
public class PersonPropertiesInfo {

	@Value("${person.age}")
	private Integer age;

	@Value("${person.lastName}")
	private String lastName;

	@Value("${person.date}")
	private String date;

	public Integer getAge() {
		return age;
	}

	public String getLastName() {
		return lastName;
	}

	public String getDate() {
		return date;
	}

}
您可以看到沒有set方法,但每個成員變量都需要加註解;

四、使用多個配置文件實現多環境情況下的配置(開發環境,生產環境)

首先創建兩個新的配置文件,一個名叫application-dev.yml,內容如下:

person:
  age: 21
  lastName: 王
  date: 2001-03-27


另一個名爲application-product.yml,內容如下:

person:
  age: 22
  lastName: 王
  date: 2001-03-27


您可以看到兩個配置文件的年齡不同,接下來修改application.yml內容如下:

server:
  port: 8087
  context-path: /springboot-yml-properties
  
spring:
  profiles:
    active: dev


此時啓動項目,訪問http://localhost:8087/springboot-yml-properties/test 您可以看到 年齡:21 姓:王 出生日期:2001-03-27年齡爲21

再修改application.yml內容如下:

server:
  port: 8087
  context-path: /springboot-yml-properties
  
spring:
  profiles:
    active: product

訪問http://localhost:8087/springboot-yml-properties/test 您可以看到 年齡:22 姓:王 出生日期:2001-03-27年齡爲22

五、使用一個配置文件實現多環境情況下的配置(開發環境,生產環境)

       可能有的小夥伴會有這樣的需求,那就是我只想使用一個配置文件,覺得還需要創建多個配置文件太麻煩了,那怎麼辦?恭喜您,yml配置文件完全可以滿足您的需求,且只需要三個英文狀態下的短橫線即可;
   首先我們修改application.yml文件內容如下:

server:  
  port: 8087  
  context-path: /springboot-yml-properties  
    
spring:  
  profiles:  
    active: dev  

---
spring:
  profiles: dev
person:
  age: 21
  lastName: 王
  date: 2001-03-27

---
spring:
  profiles: product
person:
  age: 22
  lastName: 王
  date: 2001-03-27
    然後我們刪除application-product.yml和application-dev.yml這兩個文件,接下來我們啓動項目訪問http://localhost:8087/springboot-yml-properties/test,我們會在瀏覽器看到 年齡:21 姓:王 出生日期:2001-03-27(注意年齡爲21);
    接下來我們修改application.yml的內容如下(只是把active:dev修改爲active:product):
server:  
  port: 8087  
  context-path: /springboot-yml-properties  
    
spring:  
  profiles:  
    active: product  

---
spring:
  profiles: dev
person:
  age: 21
  lastName: 王
  date: 2001-03-27

---
spring:
  profiles: product
person:
  age: 22
  lastName: 王
  date: 2001-03-27
    啓動項目,訪問http://localhost:8087/springboot-yml-properties/test,頁面顯示 年齡:22 姓:王 出生日期:2001-03-27(注意年齡爲22);

yml文件部分 end

properties文件部分start

六、多環境下使用properties文件配置

01、首先刪除項目中的yml文件,在src/main/resources路徑下建以下三個文件:

application.properties:

# 端口
server.port=8081
server.context-path=/springboot-yml-properties

spring.profiles.active=dev
application-dev.properties:
person.age=20
person.lastName=zhang
person.date=2017-04-18
application-product.properties:
person.age=22
person.lastName=wang
person.date=2017-03-16
02、

PersonPropertiesInfo.java文件的內容爲:

package com.test;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "person")
public class PersonPropertiesInfo {

	private Integer age;

	private String lastName;

	private String date;

	set get...方法忽略

}
TestController.java內容爲:
package com.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
	
	@Autowired
	private PersonPropertiesInfo personPropertiesInfo;

	@RequestMapping("/test")
	public String test() {
		return "年齡:" + personPropertiesInfo.getAge() +
				" 姓:" + personPropertiesInfo.getLastName() +
				" 出生日期:" + personPropertiesInfo.getDate();
	}

}
03、

此時啓動項目,訪問http://localhost:8081/springboot-yml-properties/test會看到瀏覽器上顯示 年齡:20 姓:zhang 出生日期:2017-04-18
04、修改application.properties文件內容如下:

# 端口
server.port=8081
server.context-path=/springboot-yml-properties

spring.profiles.active=product
此時再訪問http://localhost:8081/springboot-yml-properties/test會看到瀏覽器上顯示 年齡:22 姓:wang 出生日期:2017-03-16
properties文件部分end
看到這裏我想您已經懂了如何根據自己的需求靈活的選擇配置文件和進行配置,that's all,多謝各位看官,僅僅是本人一個學習總結~

的的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章