在ConstraintValidator中注入EntityManager

时间:2014-12-25 14:12:43

标签: java spring hibernate jpa spring-boot

您好我想在 ConstraintValidator

中注入 EntityManager

这是我的代码

CoreConfiguration

@Configuration
public class CoreConfiguration {

    @Bean
    public  MethodValidationPostProcessor methodValidationPostProcessor() {
        MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
        methodValidationPostProcessor.setValidator(validator());

        return methodValidationPostProcessor;
    }

    @Bean(name="validator")
    public static LocalValidatorFactoryBean validator() {
        LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();


        /* * ReloadableResourceBundleMessageSource messageSource = new
         * ReloadableResourceBundleMessageSource();
         * messageSource.setBasename("/WEB-INF/messages/validation");
         * localValidatorFactoryBean.setValidationMessageSource(messageSource);*/

        return localValidatorFactoryBean;
    }

}

UniqueKeyValidator.java

在这个类中,我尝试注入EntityManager,但它总是给出null

@Component
public class UniqueKeyValidator implements
        ConstraintValidator<Unique, Serializable> {

    @PersistenceContext
    private EntityManager entityManager;

    private Class<?> entityClass;
    private String uniqueField;

    public void initialize(Unique unique) {
        entityClass = unique.entity();
        uniqueField = unique.property();
    }

    @Transactional
    public boolean isValid(Serializable property,
            ConstraintValidatorContext cvContext) {

        String query = String.format("from %s where %s = :val ",entityClass.getName(), uniqueField);
        List<?> list = entityManager.createQuery(query).setParameter("val", property).getResultList();

        return list != null && list.size() > 0;
    }


}

当我测试代码时, EntityManager 总是给出null。

1 个答案:

答案 0 :(得分:1)

您使用其构造函数(UniqueKeyValidator)创建了new UniqueKeyValidator(),而不是将其注入(使用Spring DI)到您的测试类中。

CoreConfiguration无论如何都不包含此验证器,因此Spring可能根本不扫描它。所有@Component课程也必须有component:scan