我想把spring引导环境变量的值放入验证注释(@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;
这是我的申请。yml:
server:
port: 8080
spring:
data:
cassandra:
keyspace-name: message_keyspace
port: 9042
contact-points:
- localhost
validationMinMax:
min: 1
max: 3
我想把字段"min"one_answers";max"在我的属性uiType的注释字段@Min()和@Max()。有人知道怎么做吗?提前感谢您的帮助!
您可以使用自定义验证器编写自己的验证注释。在这个验证器中,你可以自动连接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;