2017-08-16 86 views
0

所以我有两个参数被Spring @Value注解注入。 minLengthmaxLength。逻辑上,minLength不得高于maxLength,反之亦然。这是我尝试过的,但失败了。Spring @Value注入字段验证注入字段

将引发异常,最大长度为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

你如何实例化注入'@ Value'的类,使用'new'或者注入其他实例。 – dabaicai

+0

这个类正在被Spring管理(使用'@ Component'注解) – XPLOT1ON

回答

2

的一个抱怨0是你的自定义验证代码,因为最大长度值不但在setMinavalue被调用的时候set(0)。

一种可能的方法是使用PostConstruct注释而不是交叉验证的自定义方法。

另一种可能的方法是实现您自己的自定义验证器(将在类级别应用)进行交叉字段验证。

+0

我明白,但是如何验证minLength大于maxLength的情况呢? – XPLOT1ON

+0

已更新的答案,在写完第一个答案后完全明白你的问题。 –

+0

PostConstruct按预期工作,谢谢 – XPLOT1ON

-1

您可以在您的bean类中添加以下注释。

@PropertySource(value = {"classpath:application.properties"}) 

并查看结果。