簡體   English   中英

使用@Configurable在JPA實體偵聽器中注入Spring bean

[英]Using @Configurable to inject spring bean in JPA entity-listener

我嘗試使用@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始終為null。

我想念什么?

好的,BankAccountAuditListener由Hibernate創建,然后可以使用spring的ApplicationContext。 可能這就是我無法在其中注入任何東西的原因。

您可以在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
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM