一、環境
- Idea 2020.1
- JDK 1.8
- maven
二、目的
通過properties檔案配置spring boot 屬性檔案, gitHub地址:https://github.com/ouyushan/ouyushan-spring-boot-samples三、步驟
3.1、點擊File -> New Project -> Spring Initializer,點擊next

3.2、在對應地方修改自己的專案資訊

3.3、選擇Web依賴,選中Spring Web,可以選擇Spring Boot版本,本次默認為2.2.6,點擊Next
3.4、編輯工程名和專案路徑,確定后點擊Finish完成

3.5、專案結構

四、添加測驗方法
4.1、新建UserController物體類
package org.ouyushan.springboot.configuration.properties.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.*; import java.util.HashMap; /** * @Description: * @Author: ouyushan * @Email: [email protected] * @Date: 2020/4/27 13:34 */ @RestController @RequestMapping("/api/user") public class UserController { @Value(value = "${ouyushan.secret}") private String secret; @Value(value = "${ouyushan.number}") private int number; @Value(value = "${ouyushan.desc}") private String desc; @GetMapping("/") public String hello() { return "Hello World Based On Spring-Boot"; } // @RequestParam 簡單型別的系結 @GetMapping("/getUser") public HashMap<String, Object> getUser(@RequestParam String username) { HashMap<String, Object> map = new HashMap<>(); map.put("title", "hello world"); map.put("username", username); map.put("secret",secret); map.put("number",number); map.put("desc",desc); return map; } }
4.2、配置默認application.properties
在resources/application.properties中配置以下資訊:ouyushan.secret=${random.value} ouyushan.number=${random.int} ouyushan.name=ouyushan ouyushan.desc=${ouyushan.name} is a domain name server.port=9090 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=Asia/Chongqing
啟動專案,訪問 http://localhost:9090/api/user/getUser?username=spring 回傳:
{ "number":-1860712823, "secret":"e1066512836d41276cbd3baf86189ac8", "title":"hello world", "username":"spring", "desc":"ouyushan is a domain name" }
4.3、配置resources/config/application.properties
ouyushan.secret=${random.value} ouyushan.number=${random.int} ouyushan.name=ouyushan-config ouyushan.desc=${ouyushan.name} is a domain name server.port=7070啟動專案,訪問 http://localhost:7070/api/user/getUser?username=spring 回傳:
{ "number":-1540619073, "secret":"352c725a9695f463f4edbcbd6dee1944", "title":"hello world", "username":"spring", "desc":"ouyushan-config is a domain name" }通過對比請求地址和回傳結果,發現resources/config/application.properties中的配置內容已覆寫resources/application.properties
五、知識點
# 示例 spring-boot-configuration-properties 外部化配置 properties檔案優先級 1. 當前目錄下的一個/config子目錄 2. 當前目錄 3. 一個classpath下的/config包 4. classpath根路徑(root) 可通過@Value取值 @Value(value = "${ouyushan.secret}") private String secret; **@ConfigurationProperties(prefix = "sample")** 讀取外部組態檔中sample 開始的屬性,自動映射到類中的欄位,并覆寫代碼中的值,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/176789.html
標籤:Java
上一篇:我天!xx.equals(null) 是什么騷操作??
下一篇:JAVA自定義注解
