我正在使用带注释的 Spring 验证机制。验证必须可在 messages_en.properties
中配置。为此,在此文件中输入 password.min=4
条目。
如何根据messageSource
bean中的设置配置@Size validator ?
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>
我已经尝试配置静态常量,但这里再次需要常量表达式。 仅供引用,需要此机制来验证 Controller 中的传入请求:
@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
最佳答案
这是不可能的。 Annotation 属性的值必须是常量,并且在编译后不能更改。使用自定义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
是一个 Validator
实现,您已为其创建了一个 bean 并使用 @Value
设置属性中的各种字段。
关于java - Spring MVC 中的可配置验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19708631/