我有一个自定义 ConstraintValidator 来验证@TelephoneNumber
注释,如下所示:
@Component
public class TelephoneNumberValidator implements ConstraintValidator<TelephoneNumber, String> {
@Autowired
ValidationHelper validationHelper;
@Override
public void initialize(TelephoneNumber telephoneNumber) { }
@Override
public boolean isValid(String telephoneNumber, ConstraintValidatorContext cxt) {
if(telephoneNumber == null) {
return true;
} else {
return validationHelper.isTelephoneNumber(telephoneNumber);
}
}
}
如您所见,它自动装配了一个 ValidationHelper 对象,该对象被标记为@Component
.
每当@Repository
我通过我坚持我的对象时,sessionFactory.getCurrentSession().persist(myobject);
我都会得到一个 NPE,因为validationHelper
它是空的。
我的休眠配置是:
@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages="uk.co.domain.repositories")
public class HibernateConfig {
static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
static final String URL = "jdbc:mysql://localhost:3306/mydatabase";
static final String USERNAME = "user";
static final String PASSWORD = "pass";
@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new org.apache.commons.dbcp2.BasicDataSource();
dataSource.setDriverClassName(DRIVER_CLASS);
dataSource.setUsername(USERNAME);
dataSource.setPassword(PASSWORD);
dataSource.setUrl(URL);
dataSource.setInitialSize(10);
return dataSource;
}
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "uk.co.domain.models" });
return sessionFactory;
}
@Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory().getObject());
return txManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
我已配置LocalValidatorFactoryBean
如下:
@Configuration
@ComponentScan(basePackages="uk.co.domain.validators")
public class ValidatorConfig {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
methodValidationPostProcessor.setValidator(validator());
return methodValidationPostProcessor;
}
@Bean
public LocalValidatorFactoryBean validator() {
LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
return localValidatorFactoryBean;
}
}
然而这并没有解决问题。MVC 表单验证工作得很好,只是 Hibernate 持久化操作失败了。
我是否需要以某种方式告诉 Hibernate 使用这个验证器?我会很感激任何指示。