前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >EnhancerBySpringCGLIB 获取getParameterAnnotations为null的解决办法

EnhancerBySpringCGLIB 获取getParameterAnnotations为null的解决办法

作者头像
跟着飞哥学编程
发布2022-11-30 21:54:01
4970
发布2022-11-30 21:54:01
举报

一、问题背景

开发程序的时候使用了aop去代理对象,然后其他地方会获取到这个代理对象并获取上面的方法注解和参数注解,运行时却发现无法获取注解,最终折腾一番终于解决。

二、问题原因

Spring项目中若开启CGLIB代理 spring.aop.proxy-target-class=true

注入接口后无法获取其实现类上注解。

通过debug得到class文件名含有EnhancerBySpringCGLIB:使用了AOP去进行代理,由于代理的对象不是接口,代理对象是由cglib代理的。

三、解决方案

正常情况获取注解方式:

代码语言:javascript
复制
Annotation[][] parameterAnnotations = method.getParameterAnnotations();

因此决定换个思路,直接获取cglib代理类的原始对象,获取原始对象上的参数注解就可以了

那我们的解决方式是加一个判断,如果是CGLIB代理类,则通过它的父类去获取方法的参数注解。?

代码语言:javascript
复制
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        if(method.getDeclaringClass().getName().contains("$$")) {
        	try {
				parameterAnnotations = method.getDeclaringClass().getSuperclass().getDeclaredMethod(method.getName(), method.getParameterTypes()).getParameterAnnotations();
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }

注:刚开始网上有解决方案是:

1.将spring.aop.proxy-target-class=true 去掉, 自动使用JDK代理。

2.使用注解解析器工具

import org.springframework.core.annotation.AnnotationUtils; public static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType) { ? ? return findAnnotation(clazz, annotationType, true); }

这种方式,小伙伴们也可以去尝试一下,但是我用的springboot框架,我的项目内还是需要用到spring的aop动态代理的。

本文参与?腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-06-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com