在 Spring Boot 项目中,编写项目代码时要求更灵活的配置,为满足要求,我们将大量的参数配置在 application.properties 或 application.yml 文件中,通过 @ConfigurationProperties
注解,我们可以更方便的获取这些参数值。
以application.yml为例:
1 application.yml
# 项目信息
text:
# 项目名称
name: textDemp
# 项目版本
version: 1.0.0
# 项目年份
copyRightYear: 2021
# 项目演示是否开启
dempEnabled: false
# 项目文件路径
profile: D:/projectFile/text
# 项目获取地址是否开启
addressEnable: true
2 创建 TextConfig 获取 yml 参数
@Component
@ConfigurationProperties(prefix = "text")
public class TextConfig {
// 项目名称
private static String name;
// 项目版本
private static String version;
// 项目年份
private static String copyRightYear;
// 项目演示是否开启
private static boolean dempEnabled;
// 项目文件路径
private static String profile;
// 项目获取地址是否开启
private static boolean addressEnable;
public static String getName() {
return name;
}
public void setName(String name) {
TextConfig.name = name;
}
public static String getVersion() {
return version;
}
public void setVersion(String version) {
TextConfig.version = version;
}
public static String getCopyRightYear() {
return copyRightYear;
}
public void setCopyRightYear(String copyRightYear) {
TextConfig.copyRightYear = copyRightYear;
}
public static boolean isDempEnabled() {
return dempEnabled;
}
public void setDempEnabled(boolean dempEnabled) {
TextConfig.dempEnabled = dempEnabled;
}
public static String getProfile() {
return profile;
}
public void setProfile(String profile) {
TextConfig.profile = profile;
}
public static boolean isAddressEnable() {
return addressEnable;
}
public void setAddressEnable(boolean addressEnable) {
TextConfig.addressEnable = addressEnable;
}
// 头像上传路径
public static String getAvatarPath(){
return getProfile() + "/avatar/";
}
// 获取文件下载路径
public static String getDownload(){
return getProfile() + "/download/";
}
// 获取文件上传路径
public static String getUpload(){
return getProfile() + "/upload/";
}
// 获取后台文件生成文件的路径
public static String getMaker(){
return getProfile() + "/maker/";
}
}
注意:如果私有属性使用static修饰,set方法不能用static修饰,否则赋值失败;当然属性可以不使用static。使用static目的只是使用时方便。
@ConfigurationProperties 参数:
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ConfigurationProperties {
@AliasFor("prefix")
String value() default "";
@AliasFor("value")
String prefix() default "";
boolean ignoreInvalidFields() default false;
boolean ignoreUnknownFields() default true;
}
ignoreInvalidFields // 属性类型解析不了配置文件中属性对应的值,默认不开启,开启后如果解析失败。程序报错。
ignoreUnknownFields //默认为开启,yml某个字段未绑定到 属性上时,程序报错。
prefix // 公共前缀
@ConfigurationProperties 绑定规则 : (宽松绑定规则)
忽略首字母大小写、下划线等
private static String copyRightYear;
// 以下都可以绑定到 属性 copyRightYear 上
yml代码:
text:
copyRightYear: 2021
copy_right_year: 2021
copy_Right_Year: 2021
copy-Right-Year: 2021
其他list、map等绑定请看@ConfigurationProperties 注解使用姿势,这一篇就够了 - 日拱一兵 - 博客园 , 当初学习时看此大佬的文章学习的。
最后,说个题外话,在开发环境没有任何问题,但是发布到 linux 服务器 (k8s)后,发现其中有个值始终获取值为null。发现此值的get方法在set之前。原因目前未知。
补充:
如果遇到此问题或者获取值时为空,在set方法加入注解即可。
@Value("${name}")public void setName(String name) {
TextConfig.name = name;
}