Spring boot 注解 ConfigurationProperties 的使用

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

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值