当前位置: 首页 > news >正文

房产交易网站建设策划案查询网站备案信息

房产交易网站建设策划案,查询网站备案信息,namesilo wordpress,金山区网站建设文章目录 1. JDK动态代理和CGLIB动态代理的区别1.1 适用范围1.2 生成的代理类1.3 调用方式 2. 问题引入3. 创建工程验证 Spring 默认采用的动态代理机制3.1 引入 Maven 依赖3.2 UserController.java3.3 UserService.java3.4 UserServiceImpl.java(save方法添加了Tra…

文章目录

  • 1. JDK动态代理和CGLIB动态代理的区别
    • 1.1 适用范围
    • 1.2 生成的代理类
    • 1.3 调用方式
  • 2. 问题引入
  • 3. 创建工程验证 Spring 默认采用的动态代理机制
    • 3.1 引入 Maven 依赖
    • 3.2 UserController.java
    • 3.3 UserService.java
    • 3.4 UserServiceImpl.java(save方法添加了@Transactional注解)
    • 3.5 User.java
    • 3.6 编写配置文件
  • 4. 测试结果及测试结果分析
    • 4.1 测试结果
    • 4.2 测试结果分析
    • 4.3 Spring Framework工程和SpringBoot工程中分别使用哪种动态代理
    • 4.4 源码分析
    • 4.5 手动指定 AOP 使用哪种动态代理
  • 5. 为什么SpringBoot默认会选用CGLIB动态代理(JDK动态代理的局限性)
    • 5.1 使用JDK动态代理时目标对象必须要实现接口
    • 5.2 使用JDK动态代理时必须要用接口来接收
    • 5.3 使用JDK动态代理时获取不到实现类方法上的注解
  • 6. 补充:调试时this指针指的是哪个对象
  • 7. 总结
  • 8. 参考资料

1. JDK动态代理和CGLIB动态代理的区别

1.1 适用范围

  • 如果要使用 JDK 动态代理,必须要保证目标类实现了接口
  • 如果要使用 CGLIB 动态代理,目标类不能使用 final 关键字进行修饰,也就是说,目标类是可继承的

1.2 生成的代理类

  • JDK 动态代理生成的代理对象会实现目标类实现的所有接口,这也是 JDK 动态代理为什么要保证目标类实现了接口的原因
  • CGLIB 动态代理生成的代理对象会继承目标类,所以说目标类不能使用 final 关键字进行修饰,因为一个类加了final 关键字就不能被继承了

1.3 调用方式

JDK 动态代理是采用反射的方式来调用目标方法,而 CGLIB 是通过子类直接调用父类的方式来调用目标方法

2. 问题引入

Spring 框架在创建代理对象时,默认情况下如果目标对象实现了至少一个接口,那么会使用 JDK 动态代理;如果目标对象没有实现任何接口,则会使用 CGLIB 动态代理

以上内容相信大家都非常熟悉,然而事实真的是这样吗,我们创建一个工程来验证一下

3. 创建工程验证 Spring 默认采用的动态代理机制

工程环境:SpringBoot 3.0.2 + JDK 17.0.7

3.1 引入 Maven 依赖

为了方便测试,我们引入以下依赖

  • Spring Web
  • MyBatis Framework
  • aspectjweaver
  • MySQL 连接驱动
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>3.0.2</version>
</dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId>
</dependency><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope>
</dependency>

我们创建几个简单的类,验证 Spring 默认采用的动态代理机制

3.2 UserController.java

import cn.edu.scau.pojo.User;
import cn.edu.scau.service.UserService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/user")
public class UserController {private final UserService userService;public UserController(UserService userService) {this.userService = userService;}@PostMapping("/save")public void save(@RequestBody User user) {userService.save(user);}}

3.3 UserService.java

import cn.edu.scau.pojo.User;public interface UserService {void save(User user);}

3.4 UserServiceImpl.java(save方法添加了@Transactional注解)

import cn.edu.scau.pojo.User;
import cn.edu.scau.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;@Service
public class UserServiceImpl implements UserService {@Transactionalpublic void save(User user) {System.out.println("保存用户:" + user);}}

3.5 User.java

public class User {}

3.6 编写配置文件

application.yml

spring:datasource:url: jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=trueusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Driver

4. 测试结果及测试结果分析

4.1 测试结果

我们在 controller 层打上断点,以 debug 的方法访问接口

在这里插入图片描述

可以看到,UserService 的类名中出现了 CGLIB 关键字,说明采用的是 CGLIB 动态代理

在这里插入图片描述

怎么回事呢,明明我的 UserServiceImpl 是实现了 UserService 接口的,为什么会使用 CGLIB 动态代理呢

4.2 测试结果分析

在 Spring Framework 中,是使用 @EnableAspectJAutoProxy 注解来开启 Spring AOP 相关功能的

我们查看一下@EnableAspectJAutoProxy 注解类的源码

在这里插入图片描述

通过源码的注释我们可以了解到:在 Spring Framework 中,proxyTargetClass 的默认取值是 false(false 表示不启用 CGLIB 动态代理),也就是说,Spring Framework 默认采用的还是使用 JDK 动态代理

难道说,Spring 源码的注释写错了???


为了进一步进行测试,我们在项目的启动类上手动指定使用 JDK 动态代理

@EnableAspectJAutoProxy(proxyTargetClass = false)

在这里插入图片描述

可以发现,Spring 默认使用的就是 JDK 动态代理

打断点后再次进行测试,发现使用的还是 CGLIB 动态代理

在这里插入图片描述

难道 @EnableAspectJAutoProxy 的 proxyTargetClass 属性无效了?

4.3 Spring Framework工程和SpringBoot工程中分别使用哪种动态代理

等一等,我们是不是遗漏了什么?

我们的测试工程使用的 SpringBoot 环境,那如果不用 SpringBoot,只用 Spring Framework 会怎么样呢


测试过程与上述测试相同,就不再赘述了

测试结果表明,在 Spring Framework 中,如果类实现了接口,默认还是使用 JDK 动态代理

4.4 源码分析

结果上面的分析,很有可能是 SpringBoot 修改了 Spring AOP 的相关配置,那我们就来一波源码分析,看一下 SpringBoot 内部到底做了什么

源码分析,找对入口很重要。那这次的入口在哪里呢?

@SpringBootApplication 是一个组合注解,该注解中使用 @EnableAutoConfiguration 实现了大量的自动装配

EnableAutoConfiguration 也是一个组合注解,在该注解上被标志了 @Import

在这里插入图片描述

在这里插入图片描述

AutoConfigurationImportSelector 类实现了 DeferredImportSelector 接口

在这里插入图片描述

DeferredImportSelector 接口中有一个 getImportGroup 方法,AutoConfigurationImportSelector 类重写了该方法

在这里插入图片描述

在这里插入图片描述

getImportGroup 方法返回了AutoConfigurationGroup 类,AutoConfigurationGroup 是 AutoConfigurationImportSelector 中的一个私有内部类,实现了 DeferredImportSelector.Group 接口

在这里插入图片描述

SpringBoot 就是通过 AutoConfigurationImportSelector.AutoConfigurationGroup 类的 process 方法来导入自动配置类的

我们在 process 方法打上断点,重新启动 SpringBoot 测试工程

在这里插入图片描述

通过调试信息,我们可以看到与 AOP 相关的自动配置是通过 org.springframework.boot.autoconfigure.aop.AopAutoConfiguration 类来进行配置的

在这里插入图片描述

我们查看 AopAutoConfiguration 类的源码,发现如果我们没有在配置文件中指定使用哪种代理,默认就会使用 CGLIB 动态代理

在这里插入图片描述

4.5 手动指定 AOP 使用哪种动态代理

通过源码我们也就可以知道,在 SpringBoot 中如果需要指定 AOP 使用哪种动态代理,需要通过 spring.aop.proxy-target-class 这个配置项来修改

在 application.yml 文件中通过 spring.aop.proxy-target-class 属性来配置

在编写文件时我们也可以看到,proxy-target-class 属性默认为 true

在这里插入图片描述

我们改为 false 之后再次启动测试工程,发现已经使用了 JDK 动态代理

在这里插入图片描述

5. 为什么SpringBoot默认会选用CGLIB动态代理(JDK动态代理的局限性)

为什么 SpringBoot 默认会选用 CGLIB 动态代理呢,当然是因为 JDK 动态代理存在一定的局限性

5.1 使用JDK动态代理时目标对象必须要实现接口

如果要使用 JDK 动态代理,必须要保证目标类实现了接口,这是由 JDK 动态代理的实现原理决定的

5.2 使用JDK动态代理时必须要用接口来接收

我们现在有 UserServiceImpl 和 UserService 两个类,此时需要在 UserContoller 中注入 UserService 类

我们通常都习惯这样写代码

@Autowired
private UserService userService;

在这种情况下,无论是使用 JDK 动态代理,还是 CGLIB 动态代理都不会出现问题


但是,如果代码是这样的呢

@Autowired
private UserServiceImpl userService;

这个时候,如果我们是使用 JDK 动态代理,那在启动时就会报错:

在这里插入图片描述

The bean is of type ‘jdk.proxy2.$Proxy59’ and implements:
cn.edu.scau.service.UserService
org.springframework.aop.SpringProxy
org.springframework.aop.framework.Advised
org.springframework.core.DecoratingProxy

Expected a bean of type ‘cn.edu.scau.service.impl.UserServiceImpl’ which implements:
cn.edu.scau.service.UserService

Action:

Consider injecting the bean as one of its interfaces or forcing the use of CGLib-based proxies by setting proxyTargetClass=true on @EnableAsync and/or @EnableCaching.


因为 JDK 动态代理是基于接口的,代理生成的对象只能赋值给接口变量

而 CGLIB 就不存在这个问题,因为 CGLIB 是通过生成目标对象子类来实现的,代理对象无论是赋值给接口还是实现类,两者都是代理对象的父类,使用 CGLIB 动态代理可以避免类型转换导致的错误

5.3 使用JDK动态代理时获取不到实现类方法上的注解

在这里插入图片描述

我们在 UserServiceImpl 类的 save 方法上添加一个自定义的 Log 注解

import java.lang.annotation.*;@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {/*** 操作名称*/String name() default "";}

同时对方法上带有 Log 注解的类进行增强

import cn.edu.scau.annotation.Log;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;/*** 切面类*/
@Component
@Aspect
public class SystemAspect {@Pointcut("@annotation(cn.edu.scau.annotation.Log)")private void pointcut() {}@Around("pointcut()")public Object around(ProceedingJoinPoint joinPoint) throws Throwable {// 通过解析 session 或 token 获取用户名// 获取被增强类和方法的信息Signature signature = joinPoint.getSignature();MethodSignature methodSignature = (MethodSignature) signature;// 获取被增强的方法对象Method method = methodSignature.getMethod();// 从方法中解析注解if (method != null) {Log logAnnotation = method.getAnnotation(Log.class);System.out.println("模块名称:" + logAnnotation.name());}// 方法名字String name = null;if (method != null) {name = method.getName();}System.out.println("方法名:" + name);// 通过工具类获取Request对象RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;HttpServletRequest request = null;if (servletRequestAttributes != null) {request = servletRequestAttributes.getRequest();}// 访问的URLString url = null;if (request != null) {url = request.getRequestURI();}System.out.println("访问的URL:" + url);// 请求方式String methodName = null;if (request != null) {methodName = request.getMethod();}System.out.println("请求方式:" + methodName);// 登录IPString ipAddress = null;if (request != null) {ipAddress = getIpAddress(request);}System.out.println("登录IP:" + ipAddress);// 操作时间System.out.println("操作时间:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));// 将操作日志保存到数据库return joinPoint.proceed();}/*** 获取 IP 地址** @param request HttpServletRequest* @return String*/public String getIpAddress(HttpServletRequest request) {String ip = request.getHeader("x-forwarded-for");if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("Proxy-Client-IP");}if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {ip = request.getHeader("WL-Proxy-Client-IP");}if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {ip = request.getRemoteAddr();}return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;}}

在这里插入图片描述

以 debug 的方式启动项目,在切面中发现获取到的注解数量为 0,获取不到任何注解,因为 UserService 接口上并没有注解(当然,我们也可以在接口上添加注解,但是这不符合我们的编码习惯)

method.getAnnotations()

在这里插入图片描述


改用 CGLIB 动态代理后,再次以 debug 的方式启动项目,在切面中发现获取到的注解数量为 2,获取到了方法上的所有注解

在这里插入图片描述

6. 补充:调试时this指针指的是哪个对象

哪个对象调用了this所在的代码块,this 指针就指向哪个对象

如果我们在打断点调试时,输出 this,会发现 this 指针指向的不是代理对象,为什么呢

在这里插入图片描述

在这里插入图片描述

因为代理对象只是对目标对象进行了增强,真正调用目标方法还是需要目标对象

以 CGLIB 动态代理为例,代理对象会保留目标对象的引用,代理对象的简单结构如下

在这里插入图片描述

我们记住,哪个对象调用了 this 所在的代码块,this 指针就指向哪个对象

在进行断点调试时,this 所在的代码块指向的对象就是目标对象,而不是代理对象

7. 总结

  • 在 Spring Framework 工程中 AOP 默认使用 JDK 动态代理
  • 为了解决使用 JDK 动态代理可能导致的类型转化异常问题,SpringBoot 默认使用 CGLIB 动态代理
  • 在 SpringBoot 中,如果需要默认使用 JDK 动态代理,可以通过配置项 spring.aop.proxy-target-class=false 来进行修改,在启动类上通过 @EnableAspectJAutoProxy(proxyTargetClass = false) 配置已无效

8. 参考资料

  • 小米二面:为什么SpringBoot使用cglib作为默认动态代理 ?AOP使用jdk动态代理会有什么问题 ?_哔哩哔哩_bilibili
  • 什么鬼?弃用JDK动态代理,Spring5 默认使用 CGLIB 了?|jdk|aop|boot|proxy|spring|framework_网易订阅 (163.com)
  • 腾讯二面:Spring AOP底层实现原理是怎么样的?JDK和CGlib动态代理有什么区别 ?_哔哩哔哩_bilibili
http://www.hkea.cn/news/417725/

相关文章:

  • 有个网站是做视频相册的网球排名即时最新排名
  • 论坛网站备案流程图优化大师怎么提交作业
  • 织梦政府网站模板百度在线入口
  • 专业做婚纱摄影网站会员制营销
  • 网站内容丰富互动营销平台
  • 阿里巴巴logo高清图谷歌seo网站推广
  • 网站如何做内链seo高手是怎样炼成的
  • 设计师个人网站建设怎样注册一个自己的平台
  • 徐州营销网站建设产品线上推广渠道
  • 绍兴市网站建设公司企业官网搭建
  • 关于网页设计的网站免费发布信息网站大全
  • 郑州新闻头条seo基础教程
  • 做网站比较大的公司朔州seo
  • 如何制作私人网站福州专业的seo软件
  • 做网站主流技术南宁在哪里推广网站
  • 老板让我做网站负责人微博营销软件
  • 教我做网站百度打开
  • 网站开发时如何兼容电商运营是做什么的
  • 河北建设银行石家庄分行招聘网站怎么申请自己的网络平台
  • vs2008 做网站搜索引擎的工作原理是什么
  • 东莞常平做网站公司app营销策划方案
  • 爱用建站 小程序重庆网站制作公司
  • 网站建设小企业案例漯河网络推广哪家好
  • wordpress 清空回收站合肥网站优化软件
  • 电站建设招聘网站智推教育seo课程
  • 做静态网站选用什么服务器站长素材网站
  • 网站建设先做前台还是后台百度认证是什么
  • 广州专业做crm系统的供应商seo网站培训班
  • 景安建网站企业网站seo方案案例
  • 山东滕州疫情最新消息今天i长沙官网seo