SpringBoot的配置文件默认是application.properties
这次记录一下application.yml的用法(优先级好像是properties,貌似是先加载的为主,具体建议百度,但是两个文件都会兼容并配置)
首先创建两个测试类
Person代码
package com.example.demo.bean;
import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Data
@ToString
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String userName;
private Boolean boss;
private Date birth;
private Integer age;
private Pet pet;
private String[] interests;
private List<String> animal;
private Map<String, Object> score;
private Set<Double> salarys;
private Map<String, List<Pet>> allPets;
}
Pet代码
package com.example.demo.bean;
import lombok.Data;
import lombok.ToString;
@Data
@ToString
public class Pet {
private String name;
private Double weight;
}
在resources下边新建application.yml文件,编写
person:
userName: zhangsan
boss: true
birth: 2019/12/9
age: 18
#interests: [篮球,足球]
interests:
- 篮球
- 足球
- 18
animal: [阿猫, 阿狗]
score: {english: 80, math: 90}
salarys:
- 9999
- 9998
pet:
name: 阿狗
weight: 99.99
allPets:
sick:
- {name: 阿狗, weight: 99.99}
- name: 阿猫
weight: 88.88
- name: 啊虫
weight: 77.77
health:
- {name: 阿花, weight: 99.99}
- {name: 阿狸, weight: 99.99}
测试并使用,在controller中编写
package com.example.demo.controller;
import com.example.demo.bean.Person;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j //lombok日志功能
@RestController
public class MyController {
@RequestMapping("/index")
public String hand1(){
log.info("收到请求");
return "hello";
}
@Autowired
Person person; //使用person组件
@RequestMapping("/person")
public Person person(){
return person;
}
}
然后运行项目,访问person