1. 程式人生 > 其它 >SpringBoot配置檔案yml詳解

SpringBoot配置檔案yml詳解

技術標籤:Javaspring bootjava

一、準備實體類

// 元件注入到容器並指定字首
@Component
@ConfigurationProperties(prefix = "person")
@Data
@ToString
public class Person {
    private String username;
    private Boolean boss;
    private Date birth;
    private Integer age;
    private Pat pat;
    private String[] intersts;
    private List<String> animal;
    private Map<String, Object> score;
    private Set<Double> salary;
    private Map<String, List<Pat>> allPats;
}

@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Pat {
    private String name;
    private Integer age;
    private Double weight;

    public Pat(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

二、配置檔案yml

person:
  username: zhangsan
  boss: true
  birth: 2019/11/1
  age: 1
  intersts:
    - 籃球
    - 足球
  animal: [小黑,小白]
  score:
    eng: 10
    cn: 20
#  score: {eng: 10, cn: 30} 以上兩種方式都可以
  salary:
    - 8888.8
    - 999.99
  pat:
    name: 嘯天犬
    age: 100
    weight: 33.9
  allPats:
    sick:
      - {name: xiaobai, weight: 88.8}
      - name: xiaoyu,
        weight: 12.1
    health:
      - name: lol,
        weight: 12.3
      - name: kkkk,
        weight: 43.3

測試controller

@GetMapping("/hello")
public Person hello() {
    return person;
}

配置檔案-自定義類繫結的配置提示

新增以下依賴即可

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

三、配置banner

jpg圖片或者txt文字,預設命名為:banner.jpg

可以修改名字,在配置檔案中指定

spring:
  banner:
    charset: utf-8
    image:
      location: niu.jpeg

詳細講義:https://www.yuque.com/atguigu/springboot/rg2p8g

雷豐陽2021版SpringBoot2零基礎入門springboot全套完整版(spring boot2)

雷豐陽2021版SpringBoot2零基礎入門springboot全套完整版(spring boot2)