01.02 Springboot2.0學習6 使用配置文件

一、Springboot2.0的配置文件

Springboot2.0的應用配置文件支持多種運行環境。

準備工作:

  • 創建一個spring-boot-web項目
  • 使用gradle
  • jdk1.8

二、配置文件使用方式

1. 命令行屬性

編譯後的程序運行:

<code>java -jar your.jar --server.port=9090/<code>
Springboot2.0學習6 使用配置文件


可以使用--添加多個程序屬性。
或在idea 設置Configurations

Springboot2.0學習6 使用配置文件

2. 使用properties文件(放在classpath下)

在src/main/resources/application.properties裡輸入:

<code>server.port=9090
spring.application.name=demoservice/<code>

3. 使用YAML文件(放在classpath下)

  • 注意對空格要求很嚴,不能使用tab代替空格
  • yaml通過空格縮進確定層級,鍵後面加冒號,冒號後面有一個空格

在src/main/resources/application.yaml裡輸入:

<code>spring:
application:
name: demoservice
server:
port: 9090/<code>

4. 擴展屬性

配置文件可以不放在classpath下,通過命令行參數指定配置文件位置:

<code>java -jar your.jar -Dspring.config.location = C:\\application.properties/<code>

5. 參數引用

配置文件裡的參數可以互相引用,如:

<code>myparam.name=myname
myparam.fullname=${myparam.name} Xie./<code>

6. 使用隨機數,prefix不能是random

Spring Boot的屬性配置文件中,可以通過使用${random}配置來產生隨機的int、float或String

<code># 隨機字符串
myvalue=${random.value}
# 隨機int
myint =${random.int}
# 隨機long
mylong =${random.long}
# 10 以內的隨機數
my10 =${random.int(10)}
# 10~20的隨機數
my1020 =${random.int[10,20]}/<code>

7. 字符串帶特殊字符需要轉義

<code>yaml:
str: 字符串可以不加引號
specialStr: "雙引號直接輸出\\n特殊字符"
specialStr2: '單引號可以轉義\\n特殊字符'/<code>

8. 使用布爾型變量

<code>yaml:
flag: false/<code>

9. 使用List可重複集合

<code>yaml:
list:
- one
- two
- two/<code>
<code>@Value("${yaml.list}")
private List<object> list; // list可重複集合/<object>/<code>

10. 使用set不可重複集合

<code>yaml:
set: [1,2,3,4]/<code>
<code>@Value("${yaml.set}")
private Set<object> set;/<object>/<code>

11. 使用Map集合

<code>yaml:
map: {k1: v1, k2: v2}/<code>
<code>@Value("${yaml.map}")
private Map<string> map;/<string>/<code>

12. 使用對象

<code>yaml:
persons:
- name: name1
age: 15
- name: name2
age: 16/<code>

引用:

<code>@Value("${yaml.persons}")
private List<person> persons; // 複合結構,集合對象/<person>/<code>

13. 獲取系統變量

<code>// java版本
@Value("#{systemProperties['java.version']}")
// 系統配置:os.name
@Value("#{systemProperties['os.name']}")/<code>

14. 表達式,支持支持SpEL表達式

<code>@Value("#{T(java.lang.Math).abs(-2020)}") // 表達式
private String mapExpression;
/<code>

三、數據校驗(JSR303)

<code>package com.xundh.demo; 


import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Email;

@Component
@ConfigurationProperties(prefix = "my")
@Validated
public class YamlEntity {
public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

@Email
private String email;
}
/<code>

當配置文件裡email的值不是email格式時,編譯會失敗。

四、讀取數據

1. 使用@Value註解讀取參數

<code>spring:
application:
name: demoservice
server:
port: 9090
my:
property_key_name: myvalue/<code>

在controller裡讀取數據:

<code>

import java.util.concurrent.atomic.AtomicLong;

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

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();

@Value("${my.property_key_name}")
String mykey;
@Value("${spring.application.name}")
String application_name;

@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
System.out.println("mykey=" + mykey);
System.out.println("application_name=" + application_name);
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}/<code>
Springboot2.0學習6 使用配置文件

如果讀取的參數不存在,程序會報java.lang.IllegalArgumentException異常,要避免這種問題可以設置默認值:

<code>@Value("${property_key_name:default_value}")

@Value("${spring.application.name:demoservice}")/<code>

2. 使用ConfigurationProperty註解,支持鬆散匹配屬性

<code>
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "my")
public class YamlEntity {
public String getMykey() {
return mykey;
}

public void setMykey(String mykey) {
this.mykey = mykey;
}

private String mykey;
}
/<code>

調用:

<code>    @Autowired
YamlEntity yamlEntity;

public void test() {
System.out.println("my value=" + yamlEntity.getMykey());

}/<code>

五、多環境配置文件

可以在項目裡使用多個SpringBoot配置文件,通過在application.properties裡設置 spring.profiles.active 指定環境。


示例:

application.properties

<code>server.port = 8080
spring.application.name = demoservice/<code>

application-dev.properties

<code>server.port = 9090
spring.application.name = demoservice/<code>

application-prod.properties

<code>server.port = 4431
spring.application.name = demoservice/<code>

通過命令行指定配置文件

<code>java -jar your.jar --spring.profiles.active=dev/<code>

也可以在配置文件裡指定spring.profiles.active的值。


分享到:


相關文章: