java - spring bean validation - 禁用某些字段的特定验证

时间:2017-11-07 09:59:05

标签: java validation spring-mvc

我的spring mvc应用程序中有一个视图模型,我需要启用或禁用某些字段的特定验证。例如,假设我有一个2个视图表单,它们将数据发送到不同的控制器方法,但两个方法都使用相同的视图模型类,如下所示:

@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){
    ...
}

这是我的观点模型的一部分:

private Integer test;

我需要在@NotNull字段上使用test注释,但只需在控制器中的method2中使用method1注释。事实上,我不需要在{{1}}中进行此验证。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:0)

删除method1中的@valid。它不会验证。

答案 1 :(得分:-1)

我认为你的方法应该是写一个像

这样的超类
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){
...
}

由于您只需要验证method2,因此超类用于method1