0

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

@Configurable
@EnableSpringConfigured
public class BankAccountAuditListener {

@PersistenceContext
private EntityManager em;

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

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

我把它放在spring配置xml文件中:

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

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

我错过了什么?

4

2 回答 2

0

好的,BankAccountAuditListener 是在 Spring 的 ApplicationContext 可以使用之前由 Hibernate 创建的。可能这就是我不能注入任何东西的原因。

于 2013-04-22T08:22:09.867 回答
0

You can use a lazily initialized bean inside your JPAEventListener class , which is initialized when the first time entity is persisted.

Then use @Configurable on lazy loaded bean. It may not be the best solution but a quick workaround

 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);
}}

And your lazy loaded bean class

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

    @Autowired
    private Environment environment;

    public void onEntityPrePersist(TransactionalEntity entity) {

        //custom logic
    }
于 2014-03-08T05:17:47.380 回答