2013-04-21 102 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 
    }