使用@Configurable在JPA实体监听器中注入spring bean

时间:2013-04-21 15:15:54

标签: java spring jpa aspectj configurable

我尝试使用@Configurable@PostPersist侦听器中注入spring bean。

@Configurable
@EnableSpringConfigured
public class BankAccountAuditListener {

@PersistenceContext
private EntityManager em;

@PostPersist
public void createAudit(BankAccount bankAccount){
    ...
}
}

监听器由@EntityListeners({BankAccountAuditListener.class})

调用

我把它放在spring配置xml-file:

<context:annotation-config/>
<context:spring-configured/>
<context:load-time-weaver/>

createAudit(...)函数中,em始终为空。

我错过了什么?

2 个答案:

答案 0 :(得分:0)

好的,BankAccountAuditListener是由Hibernate BEFORE创建的,Spring的ApplicationContext已经可以使用了。可能这就是我无法注入任何东西的原因。

答案 1 :(得分:0)

您可以在JPAEventListener类中使用延迟初始化的bean,该类在第一次实体持久化时初始化。

然后在延迟加载的bean上使用@Configurable。 它可能不是最佳解决方案,而是快速解决方法

 public class JPAEntityListener{

/**
* Hibernate JPA  EntityListEner is not spring managed and gets created via reflection by hibernate library while entitymanager is loaded.
* Inorder to inject business rules via Spring use lazy loaded bean  which makes use of   @Configurable 
 */
private CustomEntityListener listener;

public JPAEntityListener() {
    super();
}

@PrePersist
public void onEntityPrePersist(TransactionalEntity entity) {
    if (listener == null) {
        listener = new CustomEntityListener();
    }
    listener.onEntityPrePersist(entity);

}

@PreUpdate
public void onEntityPreUpdate(TransactionalEntity entity) {
    if (listener == null) {
        listener = new CustomEntityListener();
    }
    listener.onEntityPreUpdate(entity);
}}

你的懒惰加载bean类

 @Configurable(autowire = Autowire.BY_TYPE)
    public class CustomEntityListener{

    @Autowired
    private Environment environment;

    public void onEntityPrePersist(TransactionalEntity entity) {

        //custom logic
    }