2013-10-31 46 views
1

我正在使用帶批註的Spring驗證機制。驗證必須在messages_en.properties中配置。爲此,請在此文件中輸入password.min=4Spring MVC中的可配置驗證

如何根據messageSource bean中的設置配置@Size驗證器?

public class SubmitModel { 

@Size(min = "#{new Integer(messageSource[login.ok])}") //does not work. @Size expects integer value 
private String password; 

} 

bean的配置:

<bean id="messageSource" 
    class="org.springframework.context.support.ResourceBundleMessageSource"> 
    <property name="basename"> 
     <value>lang\messages</value> 
    </property> 
</bean> 

我已經嘗試配置靜態常量,但在這裏再次常量表達式的預期。 FYI,則需要該機制來驗證在控制器中的進入的請求:

@RequestMapping (value = "/device/{devicename}", method = RequestMethod.GET, produces="text/xml") 
@ResponseBody 
public String handleRequest(@PathVariable("devicename") String devicename, @Valid @ModelAttribute SubmitModel model, BindingResult errors) throws UCLoginException { ... } 

典型例子,其中該密碼必須長於login.ok值:http://my.domain.com:8080/submit/device/SPAxxxxx?name=adam&password=454321

回答

1

這是不可能的。註釋屬性的值必須是常量,編譯後不能更改。如果您需要該級別的可自定義配置,請使用自定義Validator

@Inject 
private SubmitModelValidator customValidator; 

public String handleRequest(@PathVariable("devicename") String devicename, @Valid @ModelAttribute SubmitModel model, BindingResult errors) throws UCLoginException { ... } 
    customValidator.validate(model, errors); 
    if (errors.hasErrors()) { 
     ... 
    } 
    ... 
} 

哪裏SubmitModelValidator是您用來與@Value創建一個bean,並設置各種領域,從性能的Validator實現。

+0

感謝您的建議。它讓我省了很多時間。 – luksmir