java - spring bean validation - disable specific validation on some fields

Viewed 2143

I have a view model in my spring mvc application and I need to enable or disable specific validation on some fields. For example, suppose I have a 2 view forms that sends data to different controller methods, but both methods use same view model class, something like this:

@RequestMapping(value = "/method1", method = RequestMethod.POST)
@ResponseBody
public ViewModel method1(@RequestBody @Valid ViewModel viewModel){
      ...
}

@RequestMapping(value = "/method2", method = RequestMethod.POST)
@ResponseBody
public ViewModel method2(@RequestBody @Valid ViewModel viewModel){
    ...
}

And this is part of my view model:

private Integer test;

I need to use @NotNull annotation on test field, but just in method2 in controller. In fact, I don't need this validation in method1. Is there any way for doing this?

2 Answers

Remove @valid in method1. It will not validate.

I think your approach should be to write a super class like

class ViewModel {
   @NotNull
   private Integer test;

   public Integer getTest() {
   }
}

class ViewModelSuper extends ViewModel {
   private Integer test;

   @Override
   public Integer getTest() {
   }
}


the you'll have 

@RequestMapping(value = "/method1", method = RequestMethod.POST)
@ResponseBody
public ViewModel method1(@RequestBody @Valid ViewModelSuper viewModel){
  ...
}

@RequestMapping(value = "/method2", method = RequestMethod.POST)
@ResponseBody
public ViewModel method2(@RequestBody @Valid ViewModel viewModel){
...
}

Since you only need validation for method2, the super class is used for method1

Related