java - Spring @Value注入(inject)字段之间的注入(inject)字段验证

标签 java spring

所以我有两个参数由 Spring @Value 注释注入(inject)。 minLengthmaxLength。从逻辑上讲,minLength 不得高于 maxLength,反之亦然。这是我尝试过但失败了。

抛出异常,maxLength为0,但在我的application.properties中我将其设置为7(在验证之前测试)

private int minLength;
private int maxLength;

@Min(5)
@Value("${ com.manudcamera.webapi.uuid.minLength : 5} ")
private void setMinLength(int minLength) {
    if ( minLength > this.maxLength ) throw new IllegalArgumentException("minimum length cannot be greater than maximum length | min len: " + minLength + " max len: " + this.maxLength);
    this.minLength = minLength;
}

@Max(50)
@Value("${ com.manudcamera.webapi.uuid.maxLength : 15 }")
private void setMaxLength(int maxLength) {
    if ( maxLength < this.minLength ) throw new IllegalArgumentException("maximum length cannot be greather than minimum length | min len: " + minLength + " max len: " + maxLength);
    this.maxLength = maxLength;
}

最佳答案

提示 0 的是您的自定义验证代码,因为在调用 setMinavalue 时 maxLength 值尚未设置(因此为 0)。

一种可能的方法是在执行交叉验证的自定义方法上使用 PostConstruct 注释。

另一种可能的方法是实现您自己的自定义 validator (在类级别应用)来执行跨字段验证。

关于java - Spring @Value注入(inject)字段之间的注入(inject)字段验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45705460/

相关文章:

java - Android appcompat v7 21 库中的 FadingActionBar 错误

java - Spring 安全: custom authorities by operation

java - spring boot/jpa 无法使用用户名 "@localhost"使用密码 no 连接到 mysql?

mysql - 如何使用camel将数据从mysql传输到oracle

单事务中的 Spring 集成和 JDBC

java - 我的正则表达式 {2,3} 有什么问题

java - 用模拟对象替换 JNDI 查找

spring - 硬限制连接 Spring Boot

Spring并发处理RabbitMQ消息

java - 字符串对象创建 - 双引号,怎么样?