1 回答

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超6個(gè)贊
正如 Spring 用戶手冊(cè)中詳細(xì)記錄的那樣,自調(diào)用不能與 Spring AOP 一起使用,因?yàn)?Spring AOP 使用代理。所以如果你想讓自調(diào)用觸發(fā)一個(gè)切面,請(qǐng)通過(guò) LTW (load-time weaving) 切換到完整的 AspectJ。它適用于原始 bean,不使用任何代理。
更新:如果您想避免使用本機(jī) AspectJ,而是作為(相當(dāng)蹩腳和反 AOP)解決方法想讓您的組件代理感知,當(dāng)然您可以使用自注入并使用自動(dòng)連線引用緩存方法像這樣的代理:
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();
}
}
調(diào)用bean 應(yīng)該會(huì)產(chǎn)生如下輸出doSomething():MyComponent
247760543178800
247760543178800
247760543178800
這證明緩存是這樣工作的。相反,如果您只有三行或者來(lái)自另一個(gè)(現(xiàn)已刪除)答案System.out.println(doCacheable());的奇怪、無(wú)意義的變體,那么您將在控制臺(tái)上獲得三個(gè)不同的值,即不會(huì)緩存任何內(nèi)容。 System.out.println(MyComponent.this.doCacheable());
添加回答
舉報(bào)