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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With