在写aop代码时,不知怎的出现了类似下面所写的愚蠢代码,将proceed方法放到了一个新线程。
@Around("execution(* com.ljc.service.Doc.read())")
public Object doBasicProfiling1(ProceedingJoinPoint pjp) throws Throwable {
new Thread(() -> {
try {
Object retVal = pjp.proceed();
System.out.println("结果:" + retVal);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}).start();
return " doBasicProfiling";
}
@Before("execution(* com.ljc.service.Doc.read())")
public void aa1() {
System.out.println("aa");
}
不看不知道,一看吓一跳,一个神奇的异常内容出现了。
java.lang.IllegalStateException: No MethodInvocation found: Check that an AOP invocation is in progress and that the ExposeInvocationInterceptor is upfront in the interceptor chain. Specifically, note that advices with order HIGHEST_PRECEDENCE will execute before ExposeInvocationInterceptor! In addition, ExposeInvocationInterceptor and ExposeInvocationInterceptor.currentInvocation() must be invoked from the same thread.
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.currentInvocation(ExposeInvocationInterceptor.java:78)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.getJoinPointMatch(AbstractAspectJAdvice.java:723)
at org.springframework.aop.aspectj.AspectJMethodBeforeAdvice.before(AspectJMethodBeforeAdvice.java:50)
at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:62)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:199)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:780)
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:88)
at com.ljc.aop.GlobalAopAdvice.lambda$doBasicProfiling1$0(GlobalAopAdvice.java:58)
at java.lang.Thread.run(Thread.java:748)
根据异常提示进入到对应的方法中,代码如下:
public static MethodInvocation currentInvocation() throws IllegalStateException {
MethodInvocation mi = invocation.get();
if (mi == null) {
throw new IllegalStateException(
"No MethodInvocation found: Check that an AOP invocation is in progress and that the " +
"ExposeInvocationInterceptor is upfront in the interceptor chain. Specifically, note that " +
"advices with order HIGHEST_PRECEDENCE will execute before ExposeInvocationInterceptor! " +
"In addition, ExposeInvocationInterceptor and ExposeInvocationInterceptor.currentInvocation() " +
"must be invoked from the same thread.");
}
return mi;
}
可以清楚的看出是由于mi对象为null而抛出的IllegalStateException异常。
可是原来不放在线程中执行时根本没任何问题,怎么加了线程就有问题呢?
接着看了下这个invocation的声明:
private static final ThreadLocal<MethodInvocation> invocation =
new NamedThreadLocal<>("Current AOP method invocation");
看到这里应该能明白为啥了,就是这个ThreadLocal做的鬼。
当我们用一个线程来执行proceed
方法时,下一个处理器获取MethodInvocation时就会获取不到invocation的值,导致抛出了异常信息。