亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

訪問spring bean代理引用本身

訪問spring bean代理引用本身

月關寶盒 2022-06-30 18:34:42
我對注釋@Cacheable有疑問。@CacheEviction當我在聲明它們的 bean 中調用這些方法時,aop 部分沒有被執行。造成這種情況的根本原因是 bean 訪問了它自己的實例本身,而不是訪問了 spring 代理。我讀過這個問題,據說在大多數情況下,不需要 bean 訪問代理??赡苓@些答案對我有用。問題是:還有其他方法可以使帶注釋的方法起作用嗎?或者聽起來我找到了一個 bean 需要訪問代理本身的充分理由?
查看完整描述

1 回答

?
慕哥9229398

TA貢獻1877條經驗 獲得超6個贊

正如 Spring 用戶手冊中詳細記錄的那樣,自調用不能與 Spring AOP 一起使用,因為 Spring AOP 使用代理。所以如果你想讓自調用觸發一個切面,請通過 LTW (load-time weaving) 切換到完整的 AspectJ。它適用于原始 bean,不使用任何代理。


更新:如果您想避免使用本機 AspectJ,而是作為(相當蹩腳和反 AOP)解決方法想讓您的組件代理感知,當然您可以使用自注入并使用自動連線引用緩存方法像這樣的代理:


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cache.annotation.Cacheable;

import org.springframework.stereotype.Component;


@Component

public class MyComponent {

  @Autowired

  MyComponent myComponent;


  public void doSomething() {

    System.out.println(myComponent.doCacheable());

    System.out.println(myComponent.doCacheable());

    System.out.println(myComponent.doCacheable());

  }


  @Cacheable("myCache")

  public String doCacheable() {

    return "" + System.nanoTime();

  }

}

調用bean 應該會產生如下輸出doSomething():MyComponent


247760543178800

247760543178800

247760543178800

這證明緩存是這樣工作的。相反,如果您只有三行或者來自另一個(現已刪除)答案System.out.println(doCacheable());的奇怪、無意義的變體,那么您將在控制臺上獲得三個不同的值,即不會緩存任何內容。 System.out.println(MyComponent.this.doCacheable());


查看完整回答
反對 回復 2022-06-30
  • 1 回答
  • 0 關注
  • 168 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號