记一次愚蠢的AOP使用经历

在写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的值,导致抛出了异常信息。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring AOP(面向切面编程)主要应用于解决横切关注点的问题,例如日志录、安全控制、事务管理等。其中,一个常见的应用场景是在业务方法执行前后,录日志信息。 举个例子,假设我们有一个UserService接口,其中有一个updateUser()方法用于更新用户信息。我们希望在方法执行前后,录一些日志信息,例如方法名、参数、执行时间等。这时,我们可以使用Spring AOP来实现。 首先,定义一个切面类,其中包含一个前置通知和一个后置通知,分别用于在方法执行前后执行相应操作。示例代码如下: ```java @Component @Aspect public class LoggingAspect { private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class); @Before("execution(* com.example.service.UserService.updateUser(..))") public void logBefore(JoinPoint joinPoint) { logger.info("Before method: {}", joinPoint.getSignature().getName()); logger.info("Arguments: {}", Arrays.toString(joinPoint.getArgs())); } @AfterReturning(value = "execution(* com.example.service.UserService.updateUser(..))", returning = "result") public void logAfter(JoinPoint joinPoint, Object result) { logger.info("After method: {}", joinPoint.getSignature().getName()); logger.info("Result: {}", result); } } ``` 其中,@Aspect注解表示该类为切面类,@Before和@AfterReturning注解分别表示前置通知和后置通知。这里使用Spring AOP提供的切点表达式来匹配UserService接口的updateUser()方法。 然后,在Spring配置文件中声明该切面类,并启用AOP功能。示例代码如下: ```xml <context:component-scan base-package="com.example.service" /> <aop:aspectj-autoproxy /> <bean class="com.example.aspect.LoggingAspect" /> ``` 最后,在业务逻辑中调用UserService的updateUser()方法时,Spring AOP会自动调用LoggingAspect中定义的前置通知和后置通知,录相应的日志信息。 通过这种方式,我们可以将横切关注点与业务逻辑分离,提高代码的可维护性和可重用性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值