访问 spring bean 代理引用本身

Accessing spring bean proxy reference itself

我对 @Cacheable@CacheEviction 注释有疑问。当我在声明它们的 bean 中调用这些方法时,aop 部分没有被执行。

其根本原因是 bean 访问它自己的实例本身,而不是访问 spring 代理。

我读过 this question 那里说在大多数情况下访问代理不需要 bean。

这些答案可能对我有用。问题是:

有没有其他方法可以使带注释的方法起作用?或者听起来我找到了一个需要访问代理本身的 bean 的充分理由?

正如 Spring 用户手册中详细记录的那样,自调用不能与 Spring AOP 一起使用,因为 Spring AOP 使用代理。所以如果你想让自调用触发一个方面,请切换到fullAspectJ via LTW (load-time weaving)。它与原始 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();
  }
}

MyComponent bean 上调用 doSomething() 应该产生如下输出:

247760543178800
247760543178800
247760543178800

这证明缓存是这样工作的。相反,如果你只有三行 System.out.println(doCacheable());other (now deleted) answer 中奇怪的、荒谬的变体 System.out.println(MyComponent.this.doCacheable());,然后您将在控制台上获得三个不同的值,即不会缓存任何内容。