Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Dependency Injection into JPA entity listener

I need to have a Spring dependency injected into a JPA entity listener. I know I can solve this using @Configurable and Spring's AspectJ weaver as javaagent, but this seems like a hacky solution. Is there any other way to accomplish what I'm trying to do?

like image 731
Krzaku Avatar asked Dec 04 '22 20:12

Krzaku


1 Answers

Since Hibernate 5.3 org.hibernate.resource.beans.container.spi.BeanContainer and Spring 5.1 org.springframework.orm.hibernate5.SpringBeanContainer you do not need to extra autowiring effort any more. See details of this feature in https://github.com/spring-projects/spring-framework/issues/20852

Simply annotate your EntityListener class with @Component, and do any autowiring like so:

@Component
public class MyEntityListener{

  private MySpringBean bean;

  @Autowired
  public MyEntityListener(MySpringBean bean){
    this.bean = bean;
  }

  @PrePersist
  public void prePersist(final Object entity) {
    ...
  }

}

In Spring Boot the configuration of LocalContainerEntityManagerFactoryBean is done automatically in org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration.

Outside of Spring Boot, you have to register SpringBeanContainer to Hibernate:

LocalContainerEntityManagerFactoryBean emfb = ...
 emfb.getJpaPropertyMap().put(AvailableSettings.BEAN_CONTAINER, new SpringBeanContainer(beanFactory));
like image 102
Matthias Wiedemann Avatar answered Dec 08 '22 01:12

Matthias Wiedemann