hubbabubba
hubbabubba

Reputation: 997

Service layer bean validation in Spring 5?

I need to validate beans given as argument to service layer methods in a Spring 5 application. I can get validation to work on controllers but on service layer the @Valid annotation is ignored. The service class is annotated with @Validated and an instance of it is autowired into the controller class thats making the method call.

I need to do this in a non-Boot application. I've found some instructions but they have been Boot-specific.

What am I missing here, why does this work on controller but not on the call from controller to service layer? Based on some googling, on controller level this might be somehow connected to the DispatcherServlet?

What do I need to do to make this work on service layer? The reason I want to do this on service layer is that we have validation on service layer in other apps (Jersey framework + older Spring) and others want consistency.

Upvotes: 2

Views: 915

Answers (1)

Achraf Elomari
Achraf Elomari

Reputation: 335

The reason it works for @Controller class handler methods is that Spring uses a special HandlerMethodArgumentResolver called ModelAttributeMethodProcessor which performs validation before resolving the argument to use in your handler method.

The service layer, as we call it, is just a plain bean with no additional behavior.

You can explicitly use SpringValidator

@Bean
public SpringValidator<ClassToValidate> springValidator() {
        SpringValidator<ActivityCsvDTO> springValidator = new SpringValidator<>();
        springValidator.setValidator(localValidatorFactoryBean());
        return springValidator;
    }

and directelly call validate() method

    try {
     springValidator.validate(ObjectToValidate);
    } catch (Exception e) {
      return log.error("error validation", e);
    }

Upvotes: 1

Related Questions