2017-08-16 36 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"}) 

並查看結果。