2

I have created the following annotation to be used as part of a Spring MVC validation. Unfortunately, I'm getting the following exception:

Constraint annotation types must have at least one of the element types FIELD, METHOD, TYPE or ANNOTATION_TYPE as target.

Are annotations prohibited from using ElementType.PARAMETER in the @Target annotation?

package com.jason.app.service.control.validator;


import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target(ElementType.PARAMETER)
//@Target({PARAMETER})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {ZipCodeValidator.class})
public @interface ZipCode {

    String message() default "Must be a valid 5-digit zip code";
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };

}

Usage example of the annotation:

public ResponseBody<List<Order>> getOrdersByZipCode(@Valid @ZipCode String zipCode) {
   // method body
}

Java version is Java 8.

Jason
  • 3,943
  • 12
  • 64
  • 104

1 Answers1

2

You are defining annotation on class so use ElementType.TYPE

@Target(ElementType.TYPE)

Class, interface (including annotation type), or enum declaration

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • I added a usage example of how I'm using the Parameter. It's validating a String (ultimately against a regular expression). – Jason Nov 05 '18 at 12:43
  • @Jason see https://stackoverflow.com/questions/50882444/can-spring-annotation-access-method-parameters – Ori Marko Nov 05 '18 at 12:49