是否有可能驱动@Size“ max”属性文件中的值? [英] Is it possible to drive the @Size "max" value from a properties file?

查看:87
本文介绍了是否有可能驱动@Size“ max”属性文件中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring 3.1.1.RELEASE。我有一个具有以下属性的模型

I'm using Spring 3.1.1.RELEASE. I have a model with the following attribute

import javax.validation.constraints.Size;

@Size(max=15)
private String name;

我正在运行我的控制器以验证模型

I validate the model in my controller my running

@RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView save(final Model model,
                         @Valid final MyForm myForm,

我希望 15值来自属性文件,而不是硬编码,

I would like to have the "15" value come from a properties file instead of hard-coded, but am unclear if that's possible or how its done. Any ideas?

推荐答案

这是不可能的。您提供的常量表达式因为 max 属性的值是在编译时添加的,所以无法在运行时更改注释的值,因此从读取的属性文件进行设置不可能

This is not possible. The constant expression that you provide as a value for the max attribute is added at compile time. There is no way to change the value of an annotation at runtime. Setting it from a properties file you read is therefore not possible

您可以做的是为拥有该类的类创建并注册自己的 Validator 例如,

What you can do instead is to create and register your own Validator for the your class that has that field. For example,

public class MyValidator implements Validator {

    public void validate(Object target, Errors errors) {
        MyObject obj = (MyObject) target;
        int length = getProperties().get("max.size");
        if (obj.name.length() > length) {
            errors.rejectValue("name", "String length is bigger than " + length);
        }
    }

    public boolean supports(Class<?> clazz) {
        return clazz == MyOBject.class;
    }
}

看看 Spring的验证框架

这篇关于是否有可能驱动@Size“ max”属性文件中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆