簡體   English   中英

JEE:如何攔截@PostCostruct 方法?

[英]JEE: How to intercept a @PostCostruct method?

我有一個豆子:

  • @PostConstruct注釋的void initialize()方法。
  • @PreDestroy注釋的void release()方法。
  • 其他一些方法。
  • 此外,該 bean 有一個@Interceptors注釋,定義了一些攔截器。

其中一個攔截器的方法注釋為

  • @AroundConstruct
  • @AroundInvoke
  • @AroundTimeout
  • @PostConstruct
  • @PreDestroy

在這些方法中的每一個中,我都放置了一些日志記錄,因此我可以查看攔截器方法被調用的時間和時間。 調用順序如下所示:

  • 攔截器的@AroundConstruct方法進入。 InvocationContext:目標為null ,方法為null ,構造函數已設置。
  • Beans 構造函數被調用。
  • 該調用通過 Interceptor 的@AroundConstruct方法存在。 InvocationContext:目標是 bean 實例,方法是null ,構造函數被設置。
  • 攔截器的@PostConstruct方法被調用,調用proceed() 並返回。 InvocationContext:目標是 bean 實例,方法是null ,構造函數被設置。
  • 在前一個調用完全返回后,bean 的@PostConstruct方法被調用。

我很驚訝地發現@PostConstruct不是在 bean 的@PostConstruct方法調用期間調用,而是在 bean 的構造和調用 bean 的@PostConstruct方法之間調用。 此外,bean 的@PostConstruct方法的調用根本沒有被攔截,攔截器的@PostConstruct方法和它的@AroundInvoke方法都沒有攔截。

我這邊/我的程序那邊有什么錯誤嗎?

有沒有辦法攔截 bean 的@PostConstruct方法( @PreDestroy方法也是如此)?

我需要准備上下文並用一些內容填充它們。 此外,稍后調用堆棧深處的其他方法也很高興知道該調用是由容器通過這兩種方法之一觸發的。

由於我在互聯網上找不到任何答案,我進行了一些調試並發現了以下內容(使用 WildFly 15.0.1.Final):

當 bean 被實例化時:

  • 進入攔截器的@AroundConstruct (InvocationContext: Constructor set)
  • 執行 bean 的構造函數
  • 離開攔截器的@AroundConstruct (InvocationContext: Constructur and target set)
  • 進入攔截器的@PostConstruct (InvocationContext: Constructur and target set)
  • 執行 bean 的@PostConstruct
  • 離開攔截器的@PostConstruct (InvocationContext: Constructur and target set)

這意味着你不知道調用的是哪個方法,你只知道調用了bean的@PostConstruct方法。 我想這是因為 bean 的@PostConstruct方法是作為某種攔截器執行的,但這只是我的假設。

當你執行一個 bean 的方法時:

  • 進入攔截器的@AroundInvoke (InvocationContext:方法和目標集)
  • 執行bean的方法
  • 離開攔截器的@AroundInvoke (InvocationContext:方法和目標集)

當 bean 被銷毀時:

  • 進入攔截器的@PreDestroy (InvocationContext: Target set)
  • 執行 bean 的@PreDestroy
  • 離開攔截器的@PreDestroy (InvocationContext: Target set)

我希望這對其他人也有幫助。

暫無
暫無

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

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