【问题标题】:Spring Boot Validation with environment variable使用环境变量进行 Spring Boot 验证
【发布时间】:2021-03-10 13:55:11
【问题描述】:

我想将 Spring Boot 环境变量的值放入验证注释(@Min,@Max),但我不知道该怎么做。这是我的代码:

public class MessageDTO {

@Value("${validationMinMax.min}")
private Integer min;

@JsonProperty("Message_ID")
@NotBlank(message = "messageId cannot be blank.")
@Pattern(regexp = "\\w+", message = "messageId don't suits the pattern")
private String messageId;

@JsonProperty("Message_Type")
@NotBlank(message = "messageType cannot be blank")
private String messageType;

@JsonProperty("EO_ID")
@NotBlank(message = "eoId cannot be blank")
private String eoId;

@JsonProperty("UI_Type")
@NotNull(message = "uiType cannot be null")
@Min(1)
@Max(3)
private Integer uiType;

这是我的 application.yml :

server:
  port: 8080 
spring:
  data:
    cassandra:
      keyspace-name: message_keyspace
      port: 9042
      contact-points:
        - localhost

validationMinMax:
  min: 1
  max: 3

我想将我的 yml 的字段“min”和“max”放入属性 uiType 的注释字段 @Min() 和 @Max() 中。有谁知道怎么做?提前感谢您的帮助!

【问题讨论】:

  • 有一个简单的答案,你不能。注释是静态元数据,因此无法注入。对某些注释存在的支持来自这样一个事实,即在读取注释时会评估表达式。然而,这仅适用于 spring 管理的注释,因为这些不是这样的事情,这样的支持是不可能的。

标签: java spring-boot validation


【解决方案1】:

您可以使用自定义验证器编写自己的验证注释。在这个验证器中,您可以自动装配 spring bean 并注入配置属性:

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { MyValidator.class })
@Documented
public @interface MyValidationAnnotation {
    String message() default "";

    Class<?>[] groups() default {};

    Class<? extends javax.validation.Payload>[] payload() default {};
}

验证器类:

public class MyValidator implements ConstraintValidator<MyValidationAnnotation, Integer> {

    @Autowired
    private MyService service;

    public void initialize(MyValidationAnnotation constraintAnnotation) {
      // ...
    }

    public boolean isValid(Integer value, ConstraintValidatorContext context) {
      if(service.validate(value)) {
        return true;
      } else {
        return false;
      }
    }

}

然后使用它:

@MyValidationAnnotation
Integer foo;

【讨论】:

    猜你喜欢
    • 2021-06-01
    • 2021-11-09
    • 1970-01-01
    • 2022-01-25
    • 2019-08-03
    • 2016-06-26
    • 2018-07-27
    • 1970-01-01
    • 2017-09-06
    相关资源
    最近更新 更多