Is it possible to drive the @Size “max” value from a properties file?

爱⌒轻易说出口 提交于 2019-12-13 04:30:06

问题


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,

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?


回答1:


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

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;
    }
}

Take a look at Spring's validation framework.



来源:https://stackoverflow.com/questions/18154720/is-it-possible-to-drive-the-size-max-value-from-a-properties-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!