Hello All,
In our project we are testing jpa database access with the weld-junit5 framework. The EntityManager is injected via CDI into the test class. A Bean Validation (hibernate-validator) is present in the classpath and the entity is annotated with a custom validator which implements ConstraintValidator.
So everythink works as expected and when the em.persist(entity) function is called the isValid(…) Method is also called.
The problem is, that the isValid( ) method needs a cdi-injected intstance:
public class MyValidator implements ConstraintValidator<MyValidation, TestEntity> { @Inject private MyDao myDao; // is null @Override public void initialize(MyValidation constraintAnnotation) { System.out.println("init..."); } @Override public boolean isValid(TestEntity testEntity, ConstraintValidatorContext constraintValidatorContext) { //null pointer exception is thrown here return myDao.isValid(); } public MyDao getMyDao() { return myDao; } }
The question is now: How can I turn this custom validator to a cdi bean managed instance? Is there way to get the validator instance via a simple method in order to register it with the BeanManager?
Another approach could be this way (hibernate-validator-cdi):
... import org.hibernate.validator.cdi.HibernateValidator; import org.hibernate.validator.cdi.ValidationExtension; ... @Inject @HibernateValidator private Validator validator; ... @Produces public EntityManagerFactory produceEntityManagerFactory() { // how can I force that the em uses the injected validator? }
How can I force that the em uses the injected validator?
Thanks in advance for every hint,
Tom