簡體   English   中英

自動裝配的注釋不適用於@PostLoad

[英]Autowired annotation not working with @PostLoad

我想用它來使用目錄服務從存儲庫中操作數據,但是Autowired注釋不會注入依賴項。

@Service
public class PostEntityListener {
 @PostLoad
 public <T> void onPrePersist(T obj) {
    if (obj != null) {
        String type = obj.getClass().getSimpleName();
        switch (type) {
        case "Order":
            break;
        case "OrderItem":
            try {
                OrderItem orderItem = (OrderItem) obj;
                if (orderItem != null) {
                    catalogService.save(orderItem);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;
        default:
            break;
        }
    }
 }
 @Autowired
 private CatalogService catalogService;

}

以下是我的CatalogService詳細信息:

public interface CatalogService {

   void save(OrderItem orderItem);

}

@Service
public class CatalogServiceImpl implements CatalogService {

   public void save(OrderItem orderItem) {
      catalogRepository.save(orderItem);
   }

   @Autowired
   private CatalogRepository catalogRepository;
}

首先,請記住,根據JPA規范 ,您不應該使用調用生命周期方法的相同持久化上下文(直接或間接)混亂:

通常,可移植應用程序的生命周期方法不應調用EntityManager或查詢操作,訪問其他實體實例或修改同一持久化上下文中的關系[46]。 生命周期回調方法可以修改調用它的實體的非關系狀態。

所以你調用catalogService.save(orderItem); 看起來很可疑。

關於你的主要問題,問題是EntityListener實例是由JPA提供程序而不是Spring實例化的,所以你不能直接在它們中使用Spring。 但是,您可以實現一些變通方法,閱讀此問題以獲取更多詳細信息,特別是Den B的答案很容易適應您的代碼。

我試過了,只需按照下面的代碼段進行操作即可。

@Component
public class DeptItemTransferBean {

    @Autowired
    private CatalogRepository catalogRepository;

   public void save(OrderItem orderItem) {
     catalogRepository.save(orderItem);

我用setter-injection解決了這個問題。 我使用以下代碼來注入依賴:

@Autowired
public void setCatalogService(CatalogService catalogService) {
    this.catalogService = catalogService;
}

暫無
暫無

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

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