Announcement Announcement Module
Collapse
No announcement yet.
JSR-303 dependency injection and Hibernate Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • JSR-303 dependency injection and Hibernate

    Spring 3.0.2
    Hibernate 3.5.0
    Hibernate-Validator 4.0.2.GA

    I am trying to inject Spring dependencies into a ConstraintValidator using:

    Code:
    @PersistenceContext
    private EntityManager entityManager;
    I have configured the application context with:

    Code:
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
    Which, according to the Spring documentation, should allow “custom ConstraintValidators to benefit from dependency injection like any other Spring bean”

    Within the debugger I can see Spring calling getBean to create the ConstraintValidator. Later when flush triggers the preInsert, a different ConstraintValidator is created and called. The problem is the EntityManager is null within this new ConstraintValidator. I’ve tried injecting other dependencies within the ConstraintValidator and these are always null.

    Does anyone know if it is possible to inject dependencies into a ConstraintValidator?

  • #2
    Hi,

    You can get dependencies injected into your ConstraintValidator one of two ways -- by using autowiring or by making your ConstraintValidator ApplicationContextAware and then looking up the beans in code.

    I've just implemented a ConstraintValidator that is ApplicationContextAware (to check the database for the pre-existence of a username before allowing registration of a new user) and it works perfectly.

    Cheers,
    Brien

    Comment

    Working...
    X