Spring boot 注解 ConfigurationProperties 的使用

原创自 第一勺金spring

00

最近在学习使用 spring boot。发现其中 @ConfigurationProperties这个注解使用的比较多。搜了比较多的文档都是英文,避免之后忘记,这里我也总结下它的使用方法。bash

01

开始建立一个Spring boot项目,我喜欢用官网的平台建立 start.spring.io/app

首先依赖spring-boot

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

如今 spring boot使用 .yml 格式貌似是「开发正确」,因此这里将 application 的格式改为 .yml学习

@ConfigurationProperties的做用是从配置文件中读取数据,我也不直接拿项目中的数据来举例。直接简单粗暴点。经过配置获取单个属性、集合 ,常见就这两种,不可能还从中获取 map 数据类型的数据不成。测试

获取属性数据

在 application 中添加以下对象属性数据ui

person:
    name: guozh
    age: 25
    adress: shenzheng
复制代码

建立以下对象this

@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;
    }
}

复制代码

注意:spa

  • 经过prefix 定位到以 person 开头
  • 保证 属性名字 和 application.yml 中同样,这样就能自动匹配
  • 添加 get set 方法,一个都不能少,否则就启动不成功

建立个 controller 来测试下,能不能获取.net

@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();
    }

复制代码

原创自 第一勺金

相关文章
相关标签/搜索