我正在尝试测试我的服务。当我对服务或控制器中的方法使用批注时,则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;
}
}