簡體   English   中英

在JPA實體監聽器中注入spring bean

[英]Injecting spring bean in a JPA Entity Listener

我試圖讓JPA Entity Listener通過將其標記為@Configurable來了解spring上下文。 但是注入的spring bean是null。 能夠使用相同的技術使JPA實體了解Spring上下文。 我使用Spring(core和data-jpa)作為基礎設施。 有關如何使用JPA Entity Listeners或spring data-jpa實現此目的的任何想法?

@Configurable
@Scope("singleton")
public class AggregateRootListener {
    private static Logger log = LoggerFactory.getLogger(AggregateRootListener.class);

    @Autowired
    private EventHandlerHelper eventHandlerHelper;

    @PostPersist
    @PostUpdate
    public void publishEvents(BaseAggregateRoot aggregateRoot){
        log.info(aggregateRoot.getEvents().toString());
        aggregateRoot.getEvents().stream()
            .forEach(event -> {
                eventHandlerHelper.notify(event, aggregateRoot);
                log.info("Publishing " + event + " " + aggregateRoot.toString());
            });
    }
}

和BaseAggregateRoot代碼

@Configurable
@Scope("prototype")
@MappedSuperclass
@EntityListeners(AggregateRootListener.class)
public abstract class  BaseAggregateRoot extends BaseDomain{
    public static enum AggregateStatus {
        ACTIVE, ARCHIVE
    }

    @EmbeddedId
    @AttributeOverrides({
          @AttributeOverride(name = "aggregateId", column = @Column(name = "ID", nullable = false))})
    protected AggregateId aggregateId;



    @Version
    private Long version;
}

事件監聽器機制是JPA概念,由JPA提供程序實現。 我不認為Spring會創建事件監聽器類實例 - 它們是由JPA提供程序(Hibernate,EclipseLink等)創建的。 因此,常規Spring注入不適用於事件偵聽器類實例。 這篇文章的作者似乎得出了同樣的結論。


也就是說,我在JPA事件監聽器中使用Spring托管bean。 我使用的解決方案是為了在所有不由Spring管理的類中獲取Spring bean實例而開發的。 它涉及創建以下類:

@Component
public class SpringApplicationContext implements ApplicationContextAware {
  private static ApplicationContext CONTEXT;

  public void setApplicationContext(final ApplicationContext context)
              throws BeansException {
    CONTEXT = context;
  }

  public static <T> T getBean(Class<T> clazz) { return CONTEXT.getBean(clazz); }
}

此類在初始加載時緩存Spring應用程序上下文。 然后使用上下文查找Spring托管bean。

然后使用該類就像SpringApplicationContext.getBean(FooService.class)一樣簡單。

所有常見的Spring語義,例如bean生命周期,bean范圍和傳遞依賴關系都得到了解決。

暫無
暫無

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

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