定义注解
package com.yulang.web.valitate;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Constraint(validatedBy = OrderValitator.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.FIELD})
@NotBlank
public @interface MyOrderValitate {
String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
自定义校验类
package com.yulang.web.controller;
import com.yulang.web.dto.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
@RestController
public class UserController {
@RequestMapping(value = "/user",method = RequestMethod.GET)
public List query(){
return Arrays.asList(new User(),new User(),new User());
}
@RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
public User info(@PathVariable String id){
User user = new User();
user.setUsername("jojo");
return user;
}
@RequestMapping(value = "/user/{id}",method = RequestMethod.POST)
public User create(@Valid User user){
return user;
}
}