Java Spring约束验证注解延迟执行

时间:2018-12-18 15:02:25

标签: java spring validation annotations constraints

我创建了用于检查请求标头的自定义验证,在控制器方法上添加了注释,并传递了必需的标头值,

@Constraint(validatedBy = AuthorizationValidator.class)
@Target(METHOD)
@Retention(RUNTIME)
public @interface Auth {

    @AliasFor("roles")
    String[] roles() default {};
}

和验证类:

@Log4j2
public class AuthorizationValidator implements ConstraintValidator<Auth, Object> {

    private String[] requiredRoles = {};

    @Override
    public void initialize(Auth constraintAnnotation) {
        requiredRoles = constraintAnnotation.roles();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        log.info("Checking roles");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        List<String> role = Arrays.asList(request.getHeader("role").split("-"));

        if (!role.contains(Arrays.asList(requiredRoles))) {
            throw new AuthorizationException();
        }
        return true;
    }

我将注释添加到我的控制器类中,如下所示:

    @GetMapping("/{username}")
    @Auth(roles = {"myRole"})
    public ResponseEntity<UserDto> getUser() {
    log.info("Executing controller method");
        myService.executeMethod();
        return ResponseEntity.
                status(HttpStatus.OK)
                .build();
    }

在控制器类的顶部,我还添加了注释 @Validated

这里的问题是我希望我的AuthorizationValidator在控制器方法开始做某事之前执行,但是由于某些原因,我现在总是在日志中看到:

"Executing controller method"
"Checking roles"

有没有办法强制执行约束验证?

0 个答案:

没有答案