1. 程式人生 > >Spring Boot 初級入門教程(六) —— 新增配置檔案 *.properties 及常用配置的使用(附原始碼)

Spring Boot 初級入門教程(六) —— 新增配置檔案 *.properties 及常用配置的使用(附原始碼)

Spring Boot 使用了一個全域性的配置檔案 application.properties,放在 src/main/resources 目錄下或者類路徑的 /config 下。Sping Boot的全域性配置檔案的作用是對一些預設配置的配置值進行修改。

一、新增 application.properties 檔案。

新增後目錄結構如下圖:

注意:開發過程中,儘量把配置檔案的編碼設定為 UTF-8,這樣中文不會出現亂碼,便於添加註釋。

二、常用常量配置

application.properties 提供自定義屬性的支援,這樣可以把一些應用中用到的常量配置在該檔案中,內容如下:

#################################
## 常量值配置
#################################
com.mll.constant.val.name=zhangsan
com.mll.constant.val.age=20
# 引數間直接引用
com.mll.constant.val.str=${com.mll.constant.val.name}'s age is ${com.mll.constant.val.age}.

新建一個常量值測試類 ConstantController.java,程式碼如下:

package com.menglanglang.test.springboot.controller;

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

/**
 * @desc Controller常量類
 *
 * @author 孟郎郎
 * @blog http://blog.csdn.net/tzhuwb
 * @version 1.0
 * @date 2018年7月24日下午7:15:42
 */
@RestController
@RequestMapping("/cfg")
public class ConstantController {

	// 常量值配置name
	@Value(value = "${com.mll.constant.val.name}")
	public String name;

	// 常量值配置age
	@Value("${com.mll.constant.val.age}")
	private String age;
	
	// 常量值互相應用
	@Value("${com.mll.constant.val.str}")
	private String str;

	@RequestMapping("/outStr1")
	public String printOutStr1() {
		String outStr1 = "name = " + name + ", age = " + age;
		return outStr1;
	}
	
	@RequestMapping("/outStr2")
	public String printOutStr2() {
		return str;
	}

}

啟動程式,瀏覽器訪問 http://localhost:8080/cfg/outStr1,則返回如下結果:

訪問 http://localhost:8080/cfg/outStr2,則返回如下:

如果屬性過多,也可以使用實體封裝這些屬性值。但需要在 pom.xml 檔案中新加一個依賴包,程式碼如下:

		<!-- 新增 Spring Boot 配置檔案依賴包 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<version>2.0.2.RELEASE</version>
			<optional>true</optional>
		</dependency>

新建原始碼包 entity,在其中新建實體類 PeopleInfo,內容如下:

package com.menglanglang.test.springboot.entity;

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

/**
 * @desc 人實體資訊
 *
 * @author 孟郎郎
 * @blog http://blog.csdn.net/tzhuwb
 * @version 1.0
 * @date 2018年7月24日下午8:05:11
 */
@ConfigurationProperties(prefix = "com.mll.constant.val")
@Component
public class PeopleInfo {

	/**
	 * 姓名
	 */
	private String name;

	/**
	 * 年齡
	 */
	private String age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

}

在需要使用時,直接注入實體類即可。

	@Autowired
	private PeopleInfo peopleInfo;
	
	@RequestMapping("/outStr3")
	public String printOutStr3() {
		String outStr3 = "Name = " + peopleInfo.getName() + ", Age = " + peopleInfo.getAge();
		return outStr3;
	}

訪問 http://localhost:8080/cfg/outStr3,則返回如下:

注意:如果有以下錯誤,說明實體在程式啟動時,沒有注入。

2018-07-24 21:25:57,938 INFO (DirectJDKLog.java:180)- Stopping service [Tomcat]
2018-07-24 21:25:57,951 INFO (ConditionEvaluationReportLoggingListener.java:101)- 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-07-24 21:25:58,108 ERROR (LoggingFailureAnalysisReporter.java:42)- 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field peopleInfo in com.menglanglang.test.springboot.controller.ConstantController required a bean of type 'com.menglanglang.test.springboot.entity.PeopleInfo' that could not be found.


Action:

Consider defining a bean of type 'com.menglanglang.test.springboot.entity.PeopleInfo' in your configuration.

方法一:在專案入口類 App.java 中添加註解 @EnableConfigurationProperties({PeopleInfo.class}),如圖:

方法二:在實體類上,添加註解 @Component,如圖:

三、使用自定義的配置檔案。

Spring Boot 預設讀取的配置檔名為 application.properties,所以新建後不用做任何其他檔名配置就可以獲取檔案中的配置內容,而很多情況下,如果需要自己定義一個配置檔案,比如 test.properties,那麼如何讀取該檔案中的配置。

比如 test.properties 的內容如下:

#################################
## 測試配置檔案
#################################
# 測試字串,自定義屬性,可以在Controller中讀取
com.mll.constant.val.test1=Hello Test String

在 entity 包中自定義測試實體類 TestInfo,程式碼如下:

package com.menglanglang.test.springboot.entity;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * @desc 測試實體類
 *
 * @author 孟郎郎
 * @blog http://blog.csdn.net/tzhuwb
 * @version 1.0
 * @date 2018年7月24日下午8:45:47
 */
@Configuration
@PropertySource("classpath:test.properties")
@ConfigurationProperties(prefix = "com.mll.constant.val")
public class TestInfo {

	/**
	 * 測試1
	 */
	private String test1;

	public String getTest1() {
		return test1;
	}

	public void setTest1(String test1) {
		this.test1 = test1;
	}

}

在需要使用時,直接注入實體類即可。

	@Autowired
	private TestInfo testInfo;

	@RequestMapping("/outStr4")
	public String printOutStr4() {
		String outStr4 = "test1 = " + testInfo.getTest1();
		return outStr4;
	}

訪問 http://localhost:8080/cfg/outStr4,則返回如下:

注意:使用新版本 springboot,使用上面的配置,如果是 1.5 之前的版本,則實體類中,註解方式如下:

package com.menglanglang.test.springboot.entity;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * @desc 測試實體類
 *
 * @author 孟郎郎
 * @blog http://blog.csdn.net/tzhuwb
 * @version 1.0
 * @date 2018年7月24日下午8:45:47
 */
@ConfigurationProperties(locations = "classpath:test.properties", prefix = "com.mll.constant.val")
@Component
public class TestInfo {

	/**
	 * 測試1
	 */
	private String test1;

	public String getTest1() {
		return test1;
	}

	public void setTest1(String test1) {
		this.test1 = test1;
	}

}

最後附上當前原始碼,原始碼中有點小改動,就是把兩個配置檔案都放在了 /config 目錄下,當前目錄結構如下:

原始碼下載:https://pan.baidu.com/s/10Awe7p1Ss9uRCKJNr-f0vg