springboot2.x默认使用的代理是cglib代理操作

背景 因为项目优化,打算写个日志的切面类,于是起了个springboot 工程,在这里面测试。结果在springboot 里面测试正常,能正确打印日志,但是把代码复制到实际项目中,在进入切面打印日志的时候总是报错,报空指针错误。
经调试发现每次都是在获取注解上的属性时报错。当时百思不得解。后来灵光一闪,想到可能是项目中获取到的是接口方法,而springboot是实现类的method ,所以可以拿到注解的属性。
但是仔细一想,Springboot里面也是接口,难道不应该走JDK动态代理吗?那拿到这个方法的应该也是接口的方法,带着这个疑问,我开始了我的探索之旅。
验证 springboot 项目
springboot2.x默认使用的代理是cglib代理操作
文章图片

spring 项目
springboot2.x默认使用的代理是cglib代理操作
文章图片

发现springBoot 竟然走的是cglib代理,起代理的是实现类,所以能拿到方法上注解的属性,而我的项目是个传统的spring 项目,service是接口,走的是JDK动态代理,通过切点拿到的是接口的方法,而接口上又没有注解,所以按照springboot的写法是拿不到注解的,拿不到注解也就拿不到注解属性,所以报错。
解决办法 springboot的写法

private Method getMethod(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {//获取方法签名Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); return method; } private String getAnnotationDesc(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {Method method = getMethod(joinPoint); String value = https://www.it610.com/article/method.getAnnotation(MyLog.class).value(); return value; }

spring 的写法
private Method getMethod(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {//获取方法签名Class targetClass = joinPoint.getTarget().getClass(); String methodName = joinPoint.getSignature().getName(); Class[] parameterTypes = ((MethodSignature) joinPoint.getSignature()).getParameterTypes(); Method method = targetClass.getMethod(methodName, parameterTypes); return method; }private String getAnnotationDesc(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {Method method = getMethod(joinPoint); String value = https://www.it610.com/article/method.getAnnotation(MyLog.class).value(); return value; }

可以看到spring项目的方法是先获取目标类,然后再通过目标类获取目标方法,然后再获取方法上的注解。
深度追踪 springboot 为什么将默认的代理改成了cglib,这会导致什么问题?如果我们想要事务走JDK动态代理,该如何做?
带着这些疑问,我翻阅了springboot的相关issue ,发现很多人提这个问题。
先关issue如下:
issue1
issue2
issue2
springboot团队之所以默认的代理模式设置成cglib代理,看看spring的官方团队是怎么解释的
【springboot2.x默认使用的代理是cglib代理操作】This was changed in 1.4 (see 5423). We've generally found cglib proxies less likely to cause unexpected cast exceptions.
他们认为使用cglib更不容易出现转换错误。springboot 默认的配置文件的位置在
/org/springframework/boot/spring-boot-autoconfigure/2.1.7.RELEASE/spring-boot-autoconfigure-2.1.7.RELEASE.jar!/META-INF/spring-configuration-metadata.json
{"name": "spring.aop.proxy-target-class","type": "java.lang.Boolean","description": "Whether subclass-based (CGLIB) proxies are to be created (true), as opposed to standard Java interface-based proxies (false).","defaultValue": true},

如果在事务中强制使用JDK动态代理,以往的知识告诉我们,我们需要将proxyTargetClass 设置成false,于是我们在springboot 中发现注解@EnableTransactionManagement 或者@EnableAspectJAutoProxy默认就为false,说明这里面的属性不起作用
@EnableAspectJAutoProxy(proxyTargetClass = false)@EnableTransactionManagement(proxyTargetClass = false)

同理 @EnableCaching 上的proxyTargetClass 属性也是失效的。如果偏要springboot 走JDK动态代理,那么需要在application.properties里面配置
spring.aop.proxy-target-class=false

此时项目中走的就是JDK动态代理。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    推荐阅读