简体   繁体   中英

How to use annotation validator to Optional's inner value in java

I am using java 8, springboot 2.0.0 with spring-mvc. The code below doesn't check if the value wrapped by Optional is really email or not.

import javax.validation.constraints.Email;
//...
@PostMapping("/foo")
public String foo(Optional<@Email String> email) {
  // No exception is thrown even if email is not actually email format.
  return "foo";
}

I heard of many validators works fine with Generic type, so this is embarrassing.

How can I make it work? Or, doesn't it provide the simple way?

I found that I omitted the @Validated annotation on the controller. With it, the method throws an javax.validation.ConstraintViolationException if the parameter 'email' isn't actually email.

However, I wonder why explicit @Validated is still needed. In my opinion, it might be more natural that @Validated is just implicitly configured, and springboot provides the way to deactivate it in expectedly rare cases.

import javax.validation.constraints.Email;
//...

@Controller
@Validated // With this guy, now validation works well.
public class FooConroller {

    @PostMapping("/foo")
    public String foo(Optional<@Email String> email) {
        //Now it works as expected.
        return "foo";
    }

}

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