我正在尝试使用自定义约束和验证器验证我的Hibernate实体,其中一些验证器依赖于其他服务,如配置类。我理解Spring正是为了这个目的提供了一个特定的SpringConstraintValidatorFactory
,并且在Spring中是新的,我发现了一些代码来声明相应的bean:
自定义验证器
@Service
public class MyCustomValidator implements ConstraintValidator<MyConstraint, Integer> {
@Autowire
private MyService myService;
@Override
public void initialize(MyConstraint constraint) {}
@Override
public boolean isValid(Integer someValueToValidate, ConstraintValidatorContext context) {
// doStuff
}
MyService类
@Service("MyService")
public class MyService {
private Configuration configuration;
@PostConstruct
private void map() throws IOException {
ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
InputStream stream = getClass().getClassLoader().getResourceAsStream("config/my_config.yml");
configuration = objectMapper.readValue(stream, Configuration.class);
}
private static class Configuration {
// some getters and setters
}
}
申请类
@Bean
Validator validator(AutowireCapableBeanFactory autowireCapableBeanFactory) {
ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
.configure()
.constraintValidatorFactory(new SpringConstraintValidatorFactory(autowireCapableBeanFactory))
.buildValidatorFactory();
return validatorFactory.getValidator();
}
即使使用此解决方案,在我的实体上调用验证器时,我在myService
上获得NPE。
答案 0 :(得分:1)
Hibernate使用自己的验证器,因此您应该覆盖它,并使用HibernatePropertiesCustomizer在hibernate属性中使用spring验证器。
在这里您可以找到更多详细信息:Spring Boot - Hibernate custom constraint doesn't inject Service