00
最近在学习使用 spring boot
。发现其中 @ConfigurationProperties
这个注解使用的比较多。搜了比较多的文档都是英文,避免以后忘记,这里我也总结下它的使用方法。
01
开始创建一个Spring boot
项目,我喜欢用官网的平台创建 https://start.spring.io/
首先依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
现在
spring boot
使用 .yml 格式貌似是「开发正确」,所以这里将 application 的格式改成 .yml
@ConfigurationProperties的作用是从配置文件中读取数据,我也不直接拿项目中的数据来举例。直接简单粗暴点。通过配置获取单个属性、集合 ,常见就这两种,不可能还从中获取 map 数据类型的数据不成。
获取属性数据
在 application 中添加如下对象属性数据
person:
name: guozh
age: 25
adress: shenzheng
创建如下对象
@Component
@ConfigurationProperties(prefix = "person")
public class ConfigData {
private String name;
private int age;
private String adress;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
}
注意:
- 通过
prefix
定位到以 person 开头 - 保证 属性名字 和 application.yml 中一样,这样就能自动匹配
- 添加 get set 方法,一个都不能少,不然就启动不成功
创建个 controller 来测试下,能不能获取
@RestController
public class PersonController {
@Autowired
private ConfigData configData;
@RequestMapping("/getPerson")
public String getPerson(){
return configData.getName()+" "+configData.getAge()+" "+configData.getAdress();
}
}
大部分是 spring 的内容,不用说了。直接运行
ok 已经获取。
获取集合数据
其实是同理,直接贴代码。
application.yml
class:
students:
- jack
- tom
- oliver
StudentData
@Component
@ConfigurationProperties(prefix = "class")
public class StudentData {
private List<String> students = new ArrayList<>();
public List<String> getStudents() {
return students;
}
public void setStudents(List<String> students) {
this.students = students;
}
}
@RequestMapping("/getStudent")
public String getStudent(){
return studentData.getStudents().toString();
}
本文由老郭种树原创,转载请注明:https://guozh.net/spring-boot-zhujie-configurationproperties-xiangjie/