一般来说,我们会在配置文件中自定义一些自己需要的值,比如jwt的密匙,或者一些FTP配置等信息
定义自己需要的属性
使用Spring上下文中的环境获取
使用@Value注解获取
通过@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 + '\'' +
'}';
}
}
重启项目后统一测试
接口一测试结果:
接口二测试结果:
接口三测试结果:
经过测试可以得知三种方法都可以获取配置文件中的值,其中都是可以组合使用的,比如@ConfigurationProperties+@Value等互相组合
作者:彼岸舞
时间:2021\01\12
内容关于:SpringBoot
本文来源于网络,只做技术分享,一概不负任何责任
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有