【问题标题】:AOP for inner and private methods Java用于内部和私有方法 Java 的 AOP
【发布时间】:2017-03-16 11:33:45
【问题描述】:

我正在尝试记录使用自定义接口注释的方法的执行时间。

我正在使用 Spring AOP。

但这似乎不适用于内部方法。

我认为这是 Spring AOP 的限制

@Aspect
public class BusinessProfiler {

  private static Log log = LogFactory.getLog(BusinessProfiler.class);


  @Around("execution(* *(..)) && @annotation(TimeLog)")
  public Object profile(ProceedingJoinPoint point) throws Throwable {
    long start = System.currentTimeMillis();
    Object result = point.proceed();
    String format =
        String.format("%s#%s: took [%s msec]", point.getTarget().getClass().getSimpleName(),
            MethodSignature.class.cast(point.getSignature()).getMethod().getName(),
            System.currentTimeMillis() - start);
    log.info(format);
    return result;
  }

}

除了 Spring AOP 有什么替代品吗

【问题讨论】:

    标签: java spring aspectj spring-aop


    【解决方案1】:

    如果您考虑一下 Spring 处理 AOP 注释的方式,就会清楚:

    Spring 获取您的类并将其包装在代理中,其中包含由添加的 AOP 注释动态生成的额外代码。所以只有通过代理调用的代码(即来自你的类之外的代码将被包括在内)。

    例子

    @Service
    public class Foo {
    
      public void doSomething() {
          doSomethingInternal();
      }
    
      public void doSomethingInternal() {
      }
    }
    

    如果来自另一个 Spring bean 我这样做:

    @Service
    public class Bar {
    
      @Autowired
      private Foo foo;
    
      public void execute() {
          foo.doSomething();
      }
    }
    

    只有 doSomething 会通过包装你的类的代理被调用,而不是 doSomethingInternal,它会被你的类调用。

    【讨论】:

    • 谢谢。有没有其他方法可以满足我的要求。我认为它适用于 CDI。将 CDI 拦截器与 Spring 集成的任何选项
    • 这个问题与 CDI 有什么关系? CDI 是关于依赖注入,AOP 是关于连接点拦截。如果您不愿意修改代码并且确实需要捕获内部类、通过this(而不是通过外部代理)的方法调用等,您可以随时使用use full AspectJ from within Spring,甚至完全不用Spring。
    猜你喜欢
    • 1970-01-01
    • 2021-07-03
    • 2011-05-25
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 2013-09-01
    • 2010-11-01
    • 1970-01-01
    相关资源
    最近更新 更多