SpringBoot之读取配置文件中自定义的值
概念:
一般来说,我们会在配置文件中自定义一些自己需要的值,比如jwt的密匙,或者一些FTP配置等信息
如何获取:
定义自己需要的属性
![](https://img-blog.csdnimg.cn/img_convert/76b6fc4b6f59e9c2324a2e96fdb0f829.png)
获取方式一:
使用Spring上下文中的环境获取
![](https://img-blog.csdnimg.cn/img_convert/5e7f8d67b3af70efbff5c76eda67f872.png)
![](https://img-blog.csdnimg.cn/img_convert/4c10930d028b8c4aff613827988c435f.png)
获取方式二:
使用@Value注解获取
![](https://img-blog.csdnimg.cn/img_convert/de43250296b78b9f16570e344aaf3b12.png)
![](https://img-blog.csdnimg.cn/img_convert/2abe31898d22ad04dafbae3dd273938f.png)
获取方式三:
通过@ConfigurationProperties注解获取,指定前缀,自动映射成对象,@PropertySource可以指定配置文件,使用@ConfigurationProperties注解的前提必须使用@Component注解注释成一个Bean
package com.springboot.demo.model;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* Component 定义为组件
* ConfigurationProperties 通过前缀+属性自动注入
* PropertySource 指定配置文件
*/
@Component
@ConfigurationProperties(prefix = "flower",ignoreUnknownFields = true)
@PropertySource(value = { "classpath:application.yml" })
public class Flower {
private String name;
private String age;
public Flower(String name, String age) {
this.name = name;
this.age = age;
}
public Flower() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "Flower{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
}
![](https://img-blog.csdnimg.cn/img_convert/4a3814701b8d207afe2d899742978cb5.png)
![](https://img-blog.csdnimg.cn/img_convert/28be9fa6ebf540f43c444a7492acdcb6.png)
测试:
重启项目后统一测试
接口一测试结果:
![](https://img-blog.csdnimg.cn/img_convert/c6e31849bbc6b8766050cbaf7854a82a.png)
接口二测试结果:
![](https://img-blog.csdnimg.cn/img_convert/a63a6a2f12060af4b58f67ed63a8c91e.png)
接口三测试结果:
![](https://img-blog.csdnimg.cn/img_convert/83495911e65d01bcf8a504ff9efb741e.png)
经过测试可以得知三种方法都可以获取配置文件中的值,其中都是可以组合使用的,比如@ConfigurationProperties+@Value等互相组合
作者:彼岸舞
时间:2021\01\12
内容关于:SpringBoot
本文来源于网络,只做技术分享,一概不负任何责任