James
James

Reputation: 3184

Spring require property when Spring MVC binding

I have a @RestController that has a @RequestMapping method. It takes one parameter that is an instance of a class, EmailTemplate:

   public List<Message> sendEmail(EmailTemplate emailTemplate) {
    return emailService.sendEmail(emailTemplate);
}

I would like to require that two String properties of emailTemplate not contain null or only whitespace. However, it should not be required in general. In other words, it should be required when passing to sendEmail but not necessarily in other places where the code might instantiate the class. Does Spring provide an annotated way to accomplish this?

Upvotes: 0

Views: 66

Answers (1)

JB Nizet
JB Nizet

Reputation: 692181

Yes. Spring support Bean Validation. And Bean Validation allows setting groups on validation constraints.

So, just add constraints to the two fields with a group like SendEmailGroup.class, and annotate the EmailTemplate argument of sendEmail() with @Validated(SendEmailGroup.class).

Upvotes: 1

Related Questions