1 回答

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());
添加回答
舉報