简体   繁体   中英

Spring (Boot) validation annotations for different layers on the same class

Given a web application with Spring Boot , Spring MVC and Spring Data (with MongoDB as a database) and a one class used to represent request on multiple layers (REST, service, persistence).

Is it possible to declarative specify validation constraints on the fields of the class such that some of them would apply only for certain layers (or will be ignored by some) ?

Example:

Entity (getter and setter autogenerated)

 public class User {

     private String name;

     @NotEmpty
     private String role;
 }

where @NotEmpty is JSR 303 anotation

REST API layer

role does not exist here

@RestController
public class RegisterController {

    @Autowired
    private UserService service;

    @PostMapping
    public User register(@Valid User u) {
        return service.createAppUser(u);
    }
}

Service layer

role is set by the implementation and is required by the persistence layer

@Service
public class UserService {

    @Autowired
    private UserRepo repo;

    private User createAppUser(User u) {
        u.setRole("APP_USER");
        return repo.save(u);
    }
}

where repo is Spring Data MongoRepository .

I can think of two approaches which solve this:

  1. Introduce DTO object for REST API layer
  2. Manual/ procedural validation; either using Spring Validator or something else, doesn't matter - simply nothing declarative

Both of which I don't like very much as they require lot of boilerplate and this is a trivial case.

you can use validation group and @Validated annotation.

like this:

Entity

@NotEmpty(groups = Create.class)

Method

public User register(@Validated(Create.class) User u) {
    return service.createAppUser(u);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM