Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject Spring Beans into Annotation-based Bean Validator

I wrote a custom ConstraintValidator for a MultipartFile in a Spring MVC application that looks something like this:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {MultipartFileNotEmptyValidator.class})
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER })
public @interface MultipartFileNotEmpty {
  String message() default "{errors.MultipartFileNotEmpty.message}";
  Class<?>[] groups() default {};
  Class<? extends Payload>[] payload() default {};
}

and here's the validatedBy part:

public class MultipartFileNotEmptyValidator implements ConstraintValidator<MultipartFileNotEmpty, MultipartFile>
{
  @Override
  public void initialize(MultipartFileNotEmpty annotation)
  {
    // Nothing here
  }

  @Override
  public boolean isValid(MultipartFile file, ConstraintValidatorContext context)
  {
    return !file.isEmpty();
  }
}

This one works and is incredibly simple. What I would like to do is create a second to check and make sure the MultipartFile is not too large according to a value stored in a database table. Can I inject the appropriate service into the new ConstraintValidator class somehow in order to get the information?

like image 780
Andy Avatar asked Dec 26 '22 10:12

Andy


1 Answers

It's actually nothing special at all needed to use @Autowired. From the Spring documentation:

...a ConstraintValidator implementation may have its dependencies @Autowired like any other Spring bean.

like image 189
Andy Avatar answered Dec 28 '22 06:12

Andy