使用自动装配的Spring存储库测试自定义验证。 JPA验证

时间:2019-01-23 07:10:56

标签: java spring validation

我正在尝试测试我的服务。当我对服务或控制器中的方法使用批注时,则ConstraintValidator成功自动连接存储库,当我对Entity中的字段使用批注时,存储库为null。我不明白为什么。

我的验证者:

public class MyValidator extends ConstraintValidator<UniqueNumber, Integer> {

  @Autowired
  private SomeRepository reactorRepository;

  @Override
  public void initialize(UniqueNumber annotation) {

  }

  @Override
  public boolean isValid(Integer value, ConstraintValidatorContext context) {
      ...
  } 
}

我的测试配置:

@Configuration
@EnableJpaRepositories(basePackages = "basePackage")
@EntityScan(basePackages = "basePackage")
@EnableAutoConfiguration
@ComponentScan(basePackages = "basePackage")

public class TestConfiguration {

  @PersistenceContext
  private EntityManager entityManager;

  @Bean
  public Validator validator(final AutowireCapableBeanFactory autowireCapableBeanFactory) {
      ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
              .configure()
              .constraintValidatorFactory(new SpringConstraintValidatorFactory(autowireCapableBeanFactory))
              .buildValidatorFactory();
      Validator validator = validatorFactory.getValidator();

      return validator;
  }

  @Bean
  public MethodValidationPostProcessor validationPostProcessor(final AutowireCapableBeanFactory autowireCapableBeanFactory) {
      MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
      processor.setValidator(validator(autowireCapableBeanFactory));
      return processor;
  }
}

0 个答案:

没有答案