5

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?

Andy
  • 8,749
  • 5
  • 34
  • 59
  • 1
    Make it `@Configurable`. – Dirk Lachowski Apr 08 '14 at 13:53
  • Inject it's dependencies inside a controller using a setter. There is no need to auto wire everything that has a dependency. – Bart Apr 08 '14 at 13:56
  • I think it can work. Have you try it ? If the param wont change, I would prefer load that param from database at the start of the aplpication and store it in the ServletContext. – Remi878 Apr 08 '14 at 13:57

2 Answers2

12

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.

Andy
  • 8,749
  • 5
  • 34
  • 59
-1
@Component
public class MultipartFileNotEmptyValidator

Then you can use @Autowired and have dependencies injected. Works like a charm for me.

a better oliver
  • 26,330
  • 2
  • 58
  • 66