Spring依赖注入到JPA实体侦听器

Krz*_*aku 1 java spring jpa spring-data spring-data-jpa

我需要将Spring依赖项注入到JPA实体侦听器中。我知道我可以使用@Configurable和Spring的AspectJ weaver作为javaagent来解决此问题,但这似乎是一个棘手的解决方案。还有其他方法可以完成我想做的事情吗?

Mat*_*ann 6

从Hibernate 5.3 org.hibernate.resource.beans.container.spi.BeanContainer和Spring 5.1 org.springframework.orm.hibernate5.SpringBeanContainer开始,您不再需要额外的自动装配工作。在https://github.com/spring-projects/spring-framework/issues/20852中查看此功能的详细信息

只需使用@Component注释您的EntityListener类,然后进行任何自动装配,如下所示:

@Component
public class MyEntityListener{

  private MySpringBean bean;

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

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

}
Run Code Online (Sandbox Code Playgroud)

在Spring Boot中,在org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration中自动完成LocalContainerEntityManagerFactoryBean的配置。

在Spring Boot之外,您必须将SpringBeanContainer注册到Hibernate:

LocalContainerEntityManagerFactoryBean emfb = ...
 emfb.getJpaPropertyMap().put(AvailableSettings.BEAN_CONTAINER, new SpringBeanContainer(beanFactory));
Run Code Online (Sandbox Code Playgroud)

  • 考虑使用惰性注入来解决循环依赖。对我有用。 (3认同)

Cep*_*pr0 5

另一个技巧是使用静态方法实现一个实用程序类,它可以帮助您在任何地方使用 Spring bean,而不仅仅是在托管类中:

@Component
public final class BeanUtil {

    private static ApplicationContext context;

    private BeanUtil(ApplicationContext context) {
        BeanUtil.context = context;
    }

    public static <T> T getBean(Class<T> clazz) throws BeansException {

        Assert.state(context != null, "Spring context in the BeanUtil is not been initialized yet!");
        return context.getBean(clazz);
    }
}
Run Code Online (Sandbox Code Playgroud)