【问题标题】:springboot logging with aspectj getting IllegalArgumentException: error at ::0 formal unbound in pointcut带有aspectj的springboot日志记录得到IllegalArgumentException:::0处的错误在切入点正式未绑定
【发布时间】:2016-12-19 07:29:35
【问题描述】:

我想在 springboot 项目中创建一个 aspectJ 组件,它在存在 @Loggable 注释、方法或类或两者(将考虑方法)的任何地方打印日志消息。

可记录注释:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface Loggable {
   boolean duration() default false;
}

Aspectj 类:

@Aspect
@Component
public class LogInterceptorAspect {

   @Pointcut("execution(public * ((@Loggable *)+).*(..)) && within(@Loggable *)")
   public boolean loggableDefinition(Loggable loggable) {
      return loggable.duration();
   }

   @Around("loggableDefinition(withDuration)")
   public void log(ProceedingJoinPoint joinPoint, boolean withDuration) throws Throwable {
      getLogger(joinPoint).info("start {}", joinPoint.getSignature().getName());

      StopWatch sw = new StopWatch();
      Object returnVal = null;
      try {
         sw.start();
         returnVal = joinPoint.proceed();
      } finally {
         sw.stop();
      }

      getLogger(joinPoint).info("return value: {}, duration: {}", returnVal, sw.getTotalTimeMillis()));

   }

   private Logger getLogger(JoinPoint joinPoint) {
      return LoggerFactory.getLogger(joinPoint.getSignature().getDeclaringType());
   }
}

通过上面的代码,我得到了

java.lang.IllegalArgumentException: ::0 切入点中的正式未绑定错误

怎么了?

【问题讨论】:

标签: java spring spring-boot aspectj


【解决方案1】:

基本上形式参数在 PointCut 上是未绑定的。

这是基于本文中详述的方法的替代工作示例:@AspectJ Class level Annotation Advice with Annotation as method argument

出于几个原因,我稍微修改了您的方法以避免该问题:

  • 简化了最初的 PointCut 并赋予它单一职责

    • 给它一个描述性的名称来表明它的用途
    • 通过消除对 Loggable 的依赖使其更易于重用
    • 在实施过程中与大多数可用的示例文档保持一致
  • 将建议分解为两个更简单的方法,每个方法都有一个易于理解的单一职责

    • 通过删除花哨的运算符简化了表达式
    • 将注释直接注入到使用它的 Advice 中,而不是尝试从 PointCut 传递,这感觉像是不必要的复杂性
    • 在实施过程中与大多数可用的示例文档保持一致
  • 添加了单元测试的开始以验证预期的行为,以便可以负责任地对 PointCut 和 Advice 表达式进行更改(您应该完成它)

在使用切入点/建议表达式时,我通常会尝试寻找最简单、最清晰的解决方案,并对它们进行彻底的单元测试,以确保我所期望的行为是我得到的。下一个查看您的代码的人会很感激它。

希望这会有所帮助。

package com.spring.aspects;

import static org.junit.Assert.assertEquals;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StopWatch;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = AspectInjectAnnotationTest.TestContext.class)
public class AspectInjectAnnotationTest {

    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.TYPE, ElementType.METHOD })
    public @interface Loggable {
        boolean duration() default false;
    }

    @Aspect
    public static class LogInterceptorAspect {

        @Pointcut("execution(public * *(..))")
        public void anyPublicMethod() {
        }

        @Around("anyPublicMethod() && @annotation(loggable)")
        public Object aroundLoggableMethods(ProceedingJoinPoint joinPoint, Loggable loggable) throws Throwable {
            return log(joinPoint, loggable);
        }

        @Around("(anyPublicMethod() && !@annotation(AspectInjectAnnotationTest.Loggable)) && @within(loggable)")
        public Object aroundPublicMethodsOnLoggableClasses(ProceedingJoinPoint joinPoint, Loggable loggable)
                throws Throwable {
            return log(joinPoint, loggable);
        }

        public Object log(ProceedingJoinPoint joinPoint, Loggable loggable) throws Throwable {
            getLogger(joinPoint).info("start [{}], duration [{}]", joinPoint.getSignature().getName(),
                    loggable.duration());

            StopWatch sw = new StopWatch();
            Object returnVal = null;
            try {
                sw.start();
                returnVal = joinPoint.proceed();
            } finally {
                sw.stop();
            }

            getLogger(joinPoint).info("return value: [{}], duration: [{}]", returnVal, sw.getTotalTimeMillis());

            return returnVal;
        }

        private Logger getLogger(JoinPoint joinPoint) {
            return LoggerFactory.getLogger(joinPoint.getSignature().getDeclaringType());
        }
    }

    // class level annotation - should only proxy public methods
    @Loggable(duration = true)
    public static class Service1 {

        // public - should be proxied
        public String testS1M1(String test) {
            return testProtectedM(test);
        }

        // public - should be proxied
        public String testS1M2(String test) {
            return testProtectedM(test);
        }

        // protected - should not be proxied
        protected String testProtectedM(String test) {
            return testPrivateM(test);
        }

        // private - should not be proxied
        private String testPrivateM(String test) {
            return test;
        }
    }

    // no annotation - class uses method level
    public static class Service2 {

        @Loggable
        public String testS2M1(String test) {
            return protectedMethod(test);
        }

        // no annotation - should not be proxied
        public String testS2M2(String test) {
            return protectedMethod(test);
        }

        // protected - should not be proxied
        protected String protectedMethod(String test) {
            return testPrivate(test);
        }

        // private - should not be proxied
        private String testPrivate(String test) {
            return test;
        }
    }

    // annotation - class and method level - make sure only call once
    @Loggable
    public static class Service3 {

        @Loggable
        public String testS3M1(String test) {
            return test;
        }
    }

    // context configuration for the test class
    @Configuration
    @EnableAspectJAutoProxy
    public static class TestContext {

        // configure the aspect
        @Bean
        public LogInterceptorAspect loggingAspect() {
            return new LogInterceptorAspect();
        }

        // configure a proxied beans
        @Bean
        public Service1 service1() {
            return new Service1();
        }

        // configure a proxied bean
        @Bean
        public Service2 service2() {
            return new Service2();
        }

        // configure a proxied bean
        @Bean
        public Service3 service3() {
            return new Service3();
        }
    }

    @Autowired
    private Service1 service1;

    @Autowired
    private Service2 service2;

    @Autowired
    private Service3 service3;

    @Test
    public void aspectShouldLogAsExpected() {
        // observe the output in the log, but craft this into specific
        // unit tests to assert the behavior you are expecting.

        assertEquals("service-1-method-1", service1.testS1M1("service-1-method-1")); // expect logging
        assertEquals("service-1-method-2", service1.testS1M2("service-1-method-2")); // expect logging
        assertEquals("service-2-method-1", service2.testS2M1("service-2-method-1")); // expect logging
        assertEquals("service-2-method-2", service2.testS2M2("service-2-method-2")); // expect no logging
        assertEquals("service-3-method-1", service3.testS3M1("service-3-method-1")); // expect logging once


    }
}

【讨论】:

  • 如果类和方法中存在 Loggable,那么 aroundLoggableMethods 和 aroundPublicMethodsOnLoggableClasses 都会被调用
  • 在类和方法都被注释时尝试这样的事情来防止重复调用:@Around("(anyPublicMethod() && !@annotation(AspectTest.Loggable)) && @within(loggable)") public void aroundPublicMethodsOnLoggableClasses(ProceedingJoinPoint joinPoint, Loggable loggable)
  • 很高兴您提供了一个可行的解决方案,但也许您还应该解释为什么 OP 的版本会抛出 formal unbound in pointcut: 因为切入点签名运动的方法参数尚未通过 @987654325 绑定@、this()target()@annotation() 或类似名称。我认为 OP 也应该理解 _why_ 您的解决方案看起来与他的不同。
  • 我更新了答案,使其更加完整。感谢您指出它有点缺乏细节
  • 另请注意 - 由于您只进行性能日志记录,因此您可能想查看使用 Spring 的 JamonPerformanceMonitorInterceptor 或 PerformanceMonitorInterceptor 以查看是否可以在无需编写任何代码的情况下获得相同的功能
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-07
相关资源
最近更新 更多