0

I have to implement validations for a web app that uses Spring MVC 3. The problem is that the bean class has methods like getProperty("name") and setProperty("name",valueObj). The validations have to be done on the data that is returned by passing different values to getProperty("name") , for eg: getProperty("age") should be greater than 16 and getProperty("state") should be required.

I would like to know if there is any support for validation this kind of Bean and if not, what can be the work around.

Thanks, Atif

1
  • 1
    IMHO that class is just not a bean. Commented Apr 23, 2012 at 21:41

2 Answers 2

4

I don't think so. Bean validation is performed on javabeans, i.e. class fields with getters and setters. Even if you can register a custom validator, and make validation work, binding won't work. You would need to also register a custom binder that populates your object. It becomes rather complicated. So stick to the javabeans convention.

Sign up to request clarification or add additional context in comments.

Comments

2

It sounds like you want to a custom validation class which implements org.springframework.validation.Validator.

@Component
public class MyValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return MyBean.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        MyBean myBean = (MyBean) target;

        if (StringUtils.isBlank(myBean.getProperty("state"))) {
            errors.rejectValue("state", "blank");
        }
    }

}

In your controller you would do manual validaton like follows:

@Autowired
private MyValidator myValidator;

@RequestMapping(value = "save", method = RequestMethod.POST)
public String save(@ModelAttribute("myBean") MyBean myBean, BindingResult result) {

    myValidator.validate(myBean, result);
    if (result.hasErrors()) {
        ...
    }

    ...

}

3 Comments

+1, that will work. But his bean won't be bound properly, which is before validation. So a custom binding will be needed as well. ;)
@Bozho Very good point, another argument for true JavaBeans :)
In Struts 1.x there was called as DynaBean where just had to define the bean properties in an xml without the overhead of creating each class. Does Spring provide any such method of dynamically or by configuration, creating Bean classes? Like can we define the bean and the validations in the XML?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.