title: How to apply in validator different behaviours for particular methods in spring Controller
body: <p>I would like to get answer if this approach for validation if there is possibility to customise validator for different controller methods.</p>
  
  <p>Simple validator</p>
  
  <pre><code>@Component
  public class UserDtoValidator implements Validator {
  @Autowired
  UserService userService;
  
  @Override
  public boolean supports(Class&lt;?&gt; aClass) {
      return UserDto.class.isAssignableFrom(aClass);
  }
  
  @Override
  public void validate(Object target, Errors errors) {
      UserDto userDto = (UserDto) target;
  
      }
     //how to make 'if' below to be applied only for certain method in controller
     //in this case for controller createUser method
      if (userService.findByUserName(userDto.getUserName())!=null) {
          throw new InvalidPayloadException("Creating user requires unique userName");
      }
     //second 'if' for controller updateUser method 
       if (userService.findByUserName(userDto.getUserName())==null) {
          throw new InvalidPayloadException("Updating unexisting users is not allowed");
      }
    }
  }
  </code></pre>
  
  <p>Controller:</p>
  
  <p>Here we have two opposite situations for validator:</p>
  
  <p>1 Creating user with unique userName</p>
  
  <p>2 Updating user - required userName</p>
  
  <pre><code>@Controller
  @RequestMapping(value = "/api/users")
  public class ApiUserController extends ExceptionsResolver {
  
      @Autowired
      private UserService userService;
      @Autowired
      private UserDtoValidator userDtoValidator;
      @InitBinder
      private void initBinder(WebDataBinder binder) {
      binder.setValidator(userDtoValidator);
      }
  
  
      @RequestMapping(consumes = "application/json", produces = "application/json", method = RequestMethod.POST)
      @ResponseBody
      public ResponseEntity createUser(@Valid @RequestBody UserDto userDto) throws JsonProcessingException {
          userService.saveUser(userDto);
          return new ResponseEntity(userDto, HttpStatus.ACCEPTED);
      }
  
      @RequestMapping(value = "/{userName}", consumes = "application/json", method = RequestMethod.PUT)
      @ResponseBody
      public ResponseEntity&lt;UserDto&gt; updateUser(@Valid @RequestBody UserDto userDto, @PathVariable String userName) {
           return new ResponseEntity("User updated", HttpStatus.ACCEPTED);
       }
  
  }
  </code></pre>
  
  <p>BTW I know that PUT should create new, but here I need just PUT for updating purposes. </p>