首页 > 编程语言 >【AOP问题处理】:AopContext.currentProxy()方法异常处理:java.lang.IllegalStateException: Cannot find current proxy

【AOP问题处理】:AopContext.currentProxy()方法异常处理:java.lang.IllegalStateException: Cannot find current proxy

时间:2024-06-20 16:12:22浏览次数:13  
标签:lang Set exposeProxy 代理 current proxy AOP true public

原因是代理对象内部方法的调用不会触发AOP代理。
先看代码:
自定义了一个注解:

import java.lang.annotation.ElementType;  
import java.lang.annotation.Retention;  
import java.lang.annotation.RetentionPolicy;  
import java.lang.annotation.Target;  
  
// 使用元注解来指定注解的使用场景和生命周期  
@Target({ElementType.METHOD}) // 可以用于方法
@Retention(RetentionPolicy.RUNTIME) // 运行时保留,可以通过反射获取  
public @interface Annotation1 {  
      
    // 定义一个名为value的注解属性
    String value() default "";  
}

以及一个切面类,添加了注解@Annotation1的方法会触发AOP代理:

@Aspect
public class TestAspect {

    @Around(value = "@annotation(annotation1)")
    public Object around(ProceedingJoinPoint joinPoint, Annotation1 annotation1) throws Throwable {
        // 前置逻辑
        //......
        // 方法执行
        Object resultObject = joinPoint.proceed();
        // 后置逻辑
        //......
        // 如果不需要阻止,则执行目标方法
        return resultObject;
    }
}

添加了注解@Annotation1的方法,以及报错的代码段:

@Service  
public class MyService {  
 
    public void someInternalMethod() {  
        // 获取当前代理对象  
        MyService proxy = (MyService) AopContext.currentProxy();  
        // 通过代理对象调用方法  
        proxy.method1();  
    }  
 
    @Annotation1
    public void method1() {  
        // ...  
    }  
}

本意是方法method1被调用时触发AOP代理,做一些逻辑处理,但是在Java中,默认情况下,方法内部的调用(即非通过代理的调用)是不会触发AOP(面向切面编程)代理的,所以选择使用this或AopContext.currentProxy()显式调用,这里使用的是AopContext.currentProxy(),如下:


	/**
	 * Try to return the current AOP proxy. This method is usable only if the
	 * calling method has been invoked via AOP, and the AOP framework has been set
	 * to expose proxies. Otherwise, this method will throw an IllegalStateException.
	 * @return the current AOP proxy (never returns {@code null})
	 * @throws IllegalStateException if the proxy cannot be found, because the
	 * method was invoked outside an AOP invocation context, or because the
	 * AOP framework has not been configured to expose the proxy
	 */
	public static Object currentProxy() throws IllegalStateException {
		Object proxy = currentProxy.get();
		if (proxy == null) {
			throw new IllegalStateException(
					"Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available.");
		}
		return proxy;
	}

看到这里的报错信息"Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available."就是未访问到当前线程的代理对象proxy,它提示我们将Advised对象(Advised对象:已经被Spring AOP代理包装的对象)的exposeProxy属性设置为true以使其可被访问。(exposeProxy属性表示是否暴露生成的代理类,暴露就是可手动调用

所以只要将需要代理的对象类添加注解来设置属性exposeProxy = true

@EnableAspectJAutoProxy(exposeProxy = true)

即:

@EnableAspectJAutoProxy(exposeProxy = true)
@Service  
public class MyService {  
 
    public void someInternalMethod() {  
        // 获取当前代理对象  
        MyService proxy = (MyService) AopContext.currentProxy();  
        // 通过代理对象调用方法  
        proxy.method1();  
    }  
 
    @Annotation1
    public void method1() {  
        // ...  
    }  
}

运行调用就可以成功获取MyService的代理对象,并且通过代理对象调用method1方法时,就会触发AOP代理成功

标签:lang,Set,exposeProxy,代理,current,proxy,AOP,true,public
From: https://www.cnblogs.com/masterman/p/18258770

相关文章

  • langchain入门
    LangChain为各种大型语言模型应用提供通用接口,从而简化应用程序的开发流程,轻松地构建如下所示的RAG应用 理解langchain的运作机制LangChain是一个为构建大型语言模型(LLMs)驱动的应用程序而设计的框架。它的核心目标是简化从开发到生产的整个应用程序生命周期。模块化构......
  • python中__getattr__和__setattr__
    代码:点击查看代码#!/usr/bin/envpython#!-*-coding:utf-8-*-classA(object):def__setattr__(self,key,value):self.__dict__[key]=valuedef__getattr__(self,name):return"xxx"obj=A()执行操作的代码:代码1:print(......
  • Golang - 90天从新手到大师
    开篇最近有很多小伙伴都在寻找go语言完整学习资料,我整理了一些Golang方面的知识,方便大家学习。内容从最基础的入门到项目设计,希望帮助更多想了解和学习Go语言的伙伴。因为是持续创作,所以也会持续更新。有些章节目录还没有内容,敬请期待。。创作不易,感谢大家的支持。如果看后......
  • # 猫头虎分享已解决Bug || **Out of Memory Error**: `java.lang.OutOfMemoryError:
    ......
  • 2024 年最新 Python 基于 LangChain 框架基础案例详细教程(更新中)
    LangChain框架搭建安装langchainpipinstalllangchain-ihttps://mirrors.aliyun.com/pypi/simple/安装langchain-openaipipinstalllangchain-openai-ihttps://mirrors.aliyun.com/pypi/simple/ChatOpenAI配置环境变量环境变量OPENAI_API_KEY=OpenAIAP......
  • 【golang学习之旅】Go程序快速开始 & Go程序开发的基本注意事项
    系列文章【golang学习之旅】使用VScode安装配置Go开发环境【golang学习之旅】报错:adeclaredbutnotused【golang学习之旅】Go的基本数据类型【golang学习之旅】深入理解字符串string数据类型【golang学习之旅】gomodtidy【golang学习之旅】记录一次paniccase......
  • 【漏洞复现】Zyxel NAS设备 setCookie 未授权命令注入漏洞(CVE-2024-29973)
    0x01产品简介Zyxel-NAS是指由ZyxelCommunicationsCorporation(合勤科技股份有限公司)开发和生产的网络附加存储(NetworkAttachedStorage,简称NAS)设备。NAS是一种专门用于存储和共享文件的设备,它通过网络连接到计算机、服务器或其他设备,提供集中式的文件存储和访问功能......
  • ABC 328F Good Set Query
    题意直接看题吧https://atcoder.jp/contests/abc328/tasks/abc328_f题解本题主要考了带权并查集,具体实现是在路径压缩的时候顺便维护一下边权(其中w[i]表示点i距离它的祖先的边权之和,fa[i]是点i的祖先)。依次遍历每一次询问,如果询问中的a与b拥有公共祖先,也就是在同一个并查集里......
  • golang json库 忽略 omitempty
    json库的obmitempty介绍众所周知,golang的json库有个omitempty的tag,有了它,这个json序列化的时候,如果这个字段是零值,则会忽略此字段的序列化,导致json字符串中没有对应的字符串。这对于某些人是困惑的,一般默认是没有omitempty这个tag的,但是。但是来了,但是protobuf生成的pb.......
  • GSVA: Generalized Segmentation via Multimodal Large Language Models论文阅读笔记
    Motivation&AbsGeneralizedReferringExpressionSegmentation(GRES):相比于原始的RES任务,一个文本描述里可能出现多个需要分割的物体,或者没有需要分割的物体,难点在于建模不同实体之间复杂的空间关系,以及识别不存在的描述。现有的方法如LISA难以处理GRES任务,为此作者提出了GSV......