SpringBoot yml文件語法


 

SpringBoot提供了大量的默認配置,如果要修改默認配置,需要在配置文件中修改。

 

SpringBoot默認會加載resource下的配置文件:

  • application*.yml
  • application*.yaml
  • application*.properties

這也是配置文件的加載順序,如果某個key有多個配置,則后加載的會覆蓋之前加載的配置。

yml、yaml是同一種文件,后綴寫成yml、yaml都可以。

 

一般使用application.yml。

 

 


 

 

 

springboot在不同的環境下有默認的加載文件:

  • application  開發、測試、生產都會加載,公共的
  • application-dev  只在開發環境加載(調試src/main)
  • application-test  只在測試環境加載(調試src/test)
  • application-prod  只在生產環境加載(正式打包部署)

 

 


 

 

yml文件語法

(1)普通字段:

name: zhangsan

值不加引號

 

 

(2)對象、Map

對象、Map的配置方式是一樣的。

student: #對象名、Map名
  id: 1  #配置一個屬性、一個鍵值對
  name: chy
  age: 20
  score: 100

 

值可以是對象:

server:
  port: 8080
  servlet:
    context-path: /springboot

servlet的值就是一個對象。不配置端口,默認為8080;不配置context-path,默認為/

 

 

(3)數組、List

city: [beijing,shanghai,guangzhou,shenzhen]
student: [{name: zhangsan,age: 20},{name: lisi,age: 20}]  #元素可以是對象

 

 

值,不管是key的值,還是數組元素,都不加引號。

key、value冒號分隔,冒號后面都要加一個空格,加了空格后key會變成橙色,才有效。

 

 

 


 

 

 

使用yml中的值

如果是springboot預定義的key,springboot會自動使用它。如果是自定義的key,就需要我們自己來引用。有2種引用方式。

 

(1)使用@Value

name: chy
@RestController
public class UserController {
    @Value("${name}") //使用@Value注入配置文件中的值。${}要加引號
    private String name;

    @RequestMapping("/user")
    public String handler(){
        return name; //使用
    }

}

 

不能直接${ }、"${ }"來使用配置文件中的值。

需要借助成員變量,使用@Value注入配置文件中的值,通過成員變量來引用。

 

不管成員變量是什么數據類型,${ }都需要加引號,會自動轉換為需要的類型,注入。

 

對象、Map,通過.來注入單個字段, @Value("${student.name}")

數組、List,通過下標來注入單個元素,@Value("${city[0]}")

只能注入基本類型,不能直接直接注入整個對象、Map、數組、List。

 

 

 

(2)使用@ConfigurationProperties注入對象、Map

使用@Value依次注入對象、Map的字段時,student.id,student.name,student.age,都有相同的前綴student,也可以這樣來注入:

@RestController
@ConfigurationProperties(prefix = "student") //設置前綴
public class UserController {
    private int id;
    private String name;
    private int age;
    private int score;

    public void setId(int id) {
        this.id = id;
    }

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

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

    public void setScore(int score) {
        this.score = score;
    }

    @RequestMapping("/user")
    public String handler(){
        return name; //使用
    }

}

 

設置前綴、設置對應的成員變量、並提供對應的setter方法,會自動注入該字段的值。

 

運行,效果正常,但IDEA提示:

 

其實沒啥影響,當然也可以在pom.xml中添加:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

這樣寫完@ConfigurationProperties后,在yml中配置該前綴(對象)時,會有字段提示,比如打一個student.,會有預選項id、name、age、score。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM