2013-04-21 104 views
0

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

@Configurable 
@EnableSpringConfigured 
public class BankAccountAuditListener { 

@PersistenceContext 
private EntityManager em; 

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

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

叫我把这个春天XML配置文件:

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

createAudit(...)功能,em始终为空。

我错过了什么?

回答

0

好吧,BankAccountAuditListener是由Hibernate创建的BEFORE Spring的ApplicationContext已经可以使用了。可能这是我不能在那里注入任何东西的原因。

+0

你有没有改变javaagent弹簧/ AspectJ的一个? – lbednaszynski 2013-08-28 11:13:53

+0

@marchewa,据我所知,我做过。但是经过几次迭代之后,我放弃了AspectJ方法。 – 2013-08-29 14:34:56

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 
    }