跳转至

Application.properties

Spring Boot Project 結構

src - main - java 放java code - resources 放Spring Boot 設定檔 - test - java 放測試用 java code - resources 放測試用 Spring Boot 設定檔

如何去修改放在resource資料夾的Spring Boot設定檔

用法: 使用 properties 語法 (key=value)

用途: 存放 Spring Boot 的設定值

檔名為 application

副檔名為 .properties

ex: key=value

# 不需要在=前後加上空白美化排版
count=5 
# key的名字可以帶有.符號 ,相當於中文的"的"
my.name=ts

如何讀取 Spring Boot 設定檔

需要使用 @Value 這個註解

用法: 加在 Bean 或是設定 Spring 用的 class 裏面的變數上

用途: 讀取 Spring Boot 設定檔 (application.properties) 中指定的 key 值

ex: application.properties

count=5
my.name=ts

@Value 裡面寫上 application.properties 中對應的 key

@Component
public class MyBean{
    @Value("${count}")
    private Integer number; // number=5

    @Value("${my.name}")
    private String name; // name=ts
}

使用 @Value 需要注意

  1. 可以加在帶有 @Component 或是 @Configuration 註解裡面的class
  2. 要使用 @Value 註解去載入 Spring Boot 設定檔裡面的值的時候 ,格式必須為 ”${key}”
  3. Spring Boot 設定檔裡面的值 ,類型(型別)要一致
  4. 可以設定預設值 ,當找不到對應的 key 值就會用此預設值
@Component
public class MyBean{
    @Value("${unknown:Amy}") 
    // 我們想要載入的 key 值是 unknown ,但 Spring Boot 設定檔 卻找不到 unknown 這個 key
    // 因此 Spring 就會講我們當初在 @Value 註解所寫的預設值 Amy 交給下面的 name 變數
    private String name;
}

練習

同理 count

@Value("${printer.count:20}")
private Integer count;

為甚麼要先寫到 application.properties 然後再用 @Value 載入??

通常會把這種可以調整的參數 ,統一存放在 application.properties 檔案裏面去做管理

雖然說直接使用 @PostConstruct 註解也可以在 HpPrinter 裡面對 count 的值進行初始化

這只是寫法風格上的差異

如果 application.properties 沒有對應的 key 值

org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'hp3Printer': 
Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: 
Could not resolve placeholder 'printer.count' in value "${printer.count}"

解決方法:

  1. 在 application.properties 寫上 printer.count這個key
  2. 寫上預設值 @Value("${printer.count:20}") 有就是在冒號後面加上你的預設值

檔名與副檔名 (properties /yml)

檔名一定要叫 application

有時候副檔名會叫yml ( applicatio.yml 或 application.properties 語法不同而已)

properties 語法

count=5
my.name=ts
my.age=20

yml 語法

count: 5
my:
    name: ts
    age: 20