Custom annotation validation does no validation on @pathParam in spring

时间:2016-10-20 20:06:13

标签: java spring validation spring-annotations

I wrote a custom validation to validate an id (Which is a path Param) as UUID in my @GET method of @RestController but this validation doesn't seem to be working. Even during the debug the control doesn't go to custom validation.

    @RestController
    @RequestMapping("/rateplan")
    @Validated
    public class RatePlanServiceController {

    @RequestMapping(value = "/{ratePlanId}", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public void get(@UUID @PathVariable("ratePlanId") String ratePlanId) {

        loggerFactory.warn("Get with Rate plan id {}", ratePlanId);
        loggerFactory.info("Get with Rate plan id {}", ratePlanId);
        loggerFactory.error("Get with Rate plan id {}", ratePlanId);
        loggerFactory.debug("Get with Rate plan id {}", ratePlanId);

        // return iRatePlanService.getRatePlan(ratePlanId);
    }
}

I wrote the custom annotation for validation of UUID as follow.

import org.springframework.stereotype.Component;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.regex.Pattern;

@Target(ElementType.PARAMETER)
@Constraint(validatedBy = {UUID.IdValidator.class})
@Retention(RetentionPolicy.RUNTIME)
public @interface UUID {
    String message() default "{invalid.uuid}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    @Component
    public class IdValidator implements ConstraintValidator<UUID, String> {


        private static final Pattern id_PATTERN =
                Pattern.compile("^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$");

        public boolean isValid(String value, ConstraintValidatorContext context) {

            if (!(id_PATTERN.matcher(value).matches())) {
                return false;
            }

            return true;
        }

        public void initialize(UUID parameters) {

        }

    }
}

Can anyone let me know why is it not working. Even if I provide a garbage ratePlanId like '345%#7^34' it able to go inside GET method.

1 个答案:

答案 0 :(得分:2)

通过在Application配置文件中添加bean来解决此问题。要在Spring中验证路径Param,您需要在配置类中添加此bean。

@Bean public MethodValidationPostProcessor methodValidationPostProcessor() { return new MethodValidationPostProcessor(); }