0

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?

Dave
  • 15,639
  • 133
  • 442
  • 830

1 Answers1

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724