欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > javascript >内容正文

javascript

SpringBoot - 优雅的实现【应用启动参数校验】

发布时间:2025/3/21 javascript 50 豆豆
生活随笔 收集整理的这篇文章主要介绍了 SpringBoot - 优雅的实现【应用启动参数校验】 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

文章目录

  • 需求
  • 三部曲
    • Step1 Properties类搞上Validation相关配置
    • Step2 启动测试
    • Step3 配上试试
  • 自定义校验规则
    • Step1 搞接口实现
    • Step 2 搞属性文件
    • Step 3 搞自定义校验规则
    • Step 4 验证一把
  • 源码


需求

有个参数非常非常非常非常非常重要,如果未配置 或者 配置不正确, 不能启动应用。

我们使用Spring提供的Java Validation功能来实现这个“牛逼”的需求


三部曲

Step1 Properties类搞上Validation相关配置

package com.artisan.startvalidator.config;import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import org.springframework.validation.annotation.Validated;import javax.validation.constraints.NotEmpty;/*** @author 小工匠* @version 1.0* @mark: show me the code , change the world*/@Validated @Component @Data @ConfigurationProperties(prefix = "artisan") public class ArtisanConfigProperties {@NotEmpty(message = "必须配置[artisan.code]属性")private String code;}

上面的配置就会校验在application配置文件中有没有配置artisan.code 。若没有配置,项目启动就会失败,并抛出校验异常。

温馨小提示: 在使用配置文件校验时,必须使用@configurationproperties注解,@value不支持该注解

Step2 启动测试

Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'artisan' to com.artisan.startvalidator.config.ArtisanConfigProperties failed:Property: artisan.codeValue: nullReason: 必须配置[artisan.code]属性

Step3 配上试试

随便搞个测试

当然了,根据你的需求,你也可以用框架提供的其他注解

校验规则规则说明
@Null限制只能为null
@NotNull限制必须不为null
@AssertFalse限制必须为false
@AssertTrue限制必须为true
@DecimalMax(value)限制必须为一个不大于指定值的数字
@DecimalMin(value)限制必须为一个不小于指定值的数字
@Digits(integer,fraction)限制必须为一个小数,且整数部分的位数不能超过integer,小数部分的位数不能超过fraction
@Future限制必须是一个将来的日期
@Max(value)限制必须为一个不大于指定值的数字
@Min(value)限制必须为一个不小于指定值的数字
@Past验证注解的元素值(日期类型)比当前时间早
@Pattern(value)限制必须符合指定的正则表达式
@Size(max,min)限制字符长度必须在min到max之间
@NotEmpty验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0)
@NotBlank验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格
@Email验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式

自定义校验规则

当上面这些注解都满足不了你的时候…

那干脆自定义一个

Step1 搞接口实现

自定义校验逻辑规则,实现org.springframework.validation.Validator

package com.artisan.startvalidator.validator;import com.artisan.startvalidator.config.ArtisanConfigProperties; import org.springframework.util.StringUtils; import org.springframework.validation.Errors; import org.springframework.validation.Validator;/*** @author 小工匠* @version 1.0* @mark: show me the code , change the world*/ public class ArtisanCustomConfigPropertiesValidator implements Validator {@Overridepublic boolean supports(Class<?> clazz) {// 父类.class.isAssignableFrom(子类.class)return ArtisanConfigProperties.class.isAssignableFrom(clazz);}@Overridepublic void validate(Object target, Errors errors) {ArtisanConfigProperties config = (ArtisanConfigProperties) target;if (StringUtils.isEmpty(config.getCode())) {errors.rejectValue("code", "artisan.code.empty", "[artisan.code] 属性必须要在配置文件application.properties中配置");} else if (config.getCode().length() < 8) {errors.rejectValue("id", "artisan.code.short", "[artisan.code] 属性的长度需要大于8");}} }

Step 2 搞属性文件

使用自定义校验规则就不需要在使用原生的@NotEmpty了, 删除即可

Step 3 搞自定义校验规则

注入自定义校验规则, 写个配置类,@Bean一把

package com.artisan.startvalidator.config;import com.artisan.startvalidator.validator.ArtisanCustomConfigPropertiesValidator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;/*** @author 小工匠* @version 1.0* @mark: show me the code , change the world*/@Configuration public class AppConfiguration {/*** bean的方法名必须要 configurationPropertiesValidator,否则启动的时候不会执行该校验** @return*/@Beanpublic ArtisanCustomConfigPropertiesValidator configurationPropertiesValidator() {return new ArtisanCustomConfigPropertiesValidator();} }

bean的方法名必须要 configurationPropertiesValidator,否则不生效。

Step 4 验证一把

改改application.properties 的 artisan.code

不配置试一下

可以看到错误信息就是自定义校验的输出


源码

https://github.com/yangshangwei/boot2

总结

以上是生活随笔为你收集整理的SpringBoot - 优雅的实现【应用启动参数校验】的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。