Search code examples
javaspringspring-bootspring-annotations

Can the same Custom Annotation be used to validate T and List<T>?


Good morning,

I have the following custom annotation in Java (Spring Boot):

@Target({ PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = DomainKeyValidator.class)
public @interface DomainKeyValidation {

    String message() default "";

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

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

    String domainKey() default "";
}

And the validator class:

@Component
public class DomainKeyValidator implements ConstraintValidator<DomainKeyValidation, List<String>>
{
    // Validation logic here ...
}

It works for array of Strings like this example:

@DomainKeyValidation(domainKey = "note_status") List<String> status

But it doesn't work for single String like this example:

@DomainKeyValidation(domainKey = "note_status") String status

The validation steps are the same for both the use cases except the first one where I must cycle through an array.

Are there ways to use the same annotation by changing its behavior accordingly to the input type or is it advised to create two separate implementations? Thanks in advance!


Solution

  • Instead of defining a validator for List<String>, define one that applies to a single String value:

    @Component
    public class DomainKeyValidator implements ConstraintValidator<DomainKeyValidation, String>
    {
        // Validation logic here ...
    }
    

    Then, use it as follows:

    @DomainKeyValidation(domainKey = "note_status") String status
    
    List<@DomainKeyValidation(domainKey = "note_status") String> statuses
    

    In the latter example, validation is applied to each element of the list separately.