Spring-03

1. AOP

1.1 概念

  1. AOPAspect Oriented Programming的缩写,意为:面向切面编程。他是一种可以在不修改原来的核心代码的情况下给程序动态统一进行增强的一种技术。
  2. **SpringAOP: 批量对Spring容器中bean的方法做增强,并且这种增强不会与原来方法中的代码耦合。**

1.2 快速入门

1.2.1 需求

  1. 要求让_08_SpringAOP模块中service包下所有类的所有方法在调用前都输出:方法被调用了。

1.2.2 准备工作

①添加依赖

需要添加SpringIOC相关依赖和AOP相关依赖。

  1. <!--SpringIOC相关依赖-->
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-context</artifactId>
  5. <version>5.1.9.RELEASE</version>
  6. </dependency>
  7. <!--AOP相关依赖-->
  8. <dependency>
  9. <groupId>org.aspectj</groupId>
  10. <artifactId>aspectjweaver</artifactId>
  11. <version>1.8.13</version>
  12. </dependency>

②相关bean要注入容器中

开启组件扫描

  1. <context:component-scan base-package="com.sangeng"></context:component-scan>

加@Service注解

  1. @Service
  2. public class PhoneService {
  3. public void deleteAll(){
  4. System.out.println("PhoneService中deleteAll的核心代码");
  5. }
  6. }
  1. @Service
  2. public class UserService {
  3. public void deleteAll(){
  4. System.out.println("UserService中deleteAll的核心代码");
  5. }
  6. }

1.2.3 实现AOP

①开启AOP注解支持

使用aop:aspectj-autoproxy标签

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
  6. <!--开启组件扫描-->
  7. <context:component-scan base-package="com.sangeng"></context:component-scan>
  8. <!--开启aop注解支持-->
  9. <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
  10. </beans>

②创建切面类

创建一个类,在类上加上@Component和@Aspect

使用@Pointcut注解来指定要被增强的方法

使用@Before注解来给我们的增强代码所在的方法进行标识,并且指定了增强代码是在被增强方法执行之前执行的。

  1. @Component
  2. @Aspect
  3. public class MyAspect {
  4. // 用Pointcut注解中的属性来指定对哪些方法进行增强
  5. @Pointcut("execution(* com.sangeng.service.*.*(..))")
  6. public void pt(){}
  7. /*
  8. 用@Before注解来指定该方法中是增强的代码,并且是在被增强方法执行前执行的
  9. @Before的属性写上加了@Pointcut注解的方法: 方法名()
  10. */
  11. @Before("pt()")
  12. public void methodbefore(){
  13. System.out.println("方法被调用了");
  14. }
  15. }

1.2.4 测试

  1. public static void main(String[] args) {
  2. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  3. PhoneService phoneService = applicationContext.getBean(PhoneService.class);
  4. UserService userService = applicationContext.getBean(UserService.class);
  5. phoneService.deleteAll();
  6. }

1.3 AOP核心概念

  • Joinpoint(连接点):所谓连接点是指那些可以被增强到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点

  • Pointcut(切入点):所谓切入点是指被增强的连接点(方法)

  • Advice(通知/ 增强):所谓通知是指具体增强的代码

  • Target(目标对象):被增强的对象就是目标对象

  • Aspect(切面):是切入点和通知(引介)的结合

  • Proxy (代理):一个类被 AOP 增强后,就产生一个结果代理类

1.4 切点确定

1.4.1 切点表达式

  1. 可以使用切点表达式来表示要对哪些方法进行增强。

写法:execution([修饰符] 返回值类型 包名.类名.方法名(参数))

  • 访问修饰符可以省略,大部分情况下省略
  • 返回值类型、包名、类名、方法名可以使用星号* 代表任意
  • 包名与类名之间一个点 . 代表当前包下的类,两个点 .. 表示当前包及其子包下的类
  • 参数列表可以使用两个点 .. 表示任意个数,任意类型的参数列表

例如:

  1. execution(* com.sangeng.service.*.*(..)) 表示com.sangeng.service包下任意类,方法名任意,参数列表任意,返回值类型任意
  2. execution(* com.sangeng.service..*.*(..)) 表示com.sangeng.service包及其子包下任意类,方法名任意,参数列表任意,返回值类型任意
  3. execution(* com.sangeng.service.*.*()) 表示com.sangeng.service包下任意类,方法名任意,要求方法不能有参数,返回值类型任意
  4. execution(* com.sangeng.service.*.delete*(..)) 表示com.sangeng.service包下任意类,要求方法不能有参数,返回值类型任意,方法名要求已delete开头

1.4.2 切点函数@annotation

  1. 我们也可以在要增强的方法上加上注解。然后使用@annotation来表示对加了什么注解的方法进行增强。

写法:@annotation(注解的全类名)

例如:

定义注解如下

  1. @Target({ElementType.METHOD})//该注解可以加在方法上
  2. @Retention(RetentionPolicy.RUNTIME)
  3. public @interface InvokeLog {
  4. }

给需要增强的方法增加注解

  1. @Service
  2. public class PhoneService {
  3. @InvokeLog
  4. public void deleteAll(){
  5. System.out.println("PhoneService中deleteAll的核心代码");
  6. }
  7. }

切面类中使用@annotation来确定要增强的方法

  1. @Component
  2. @Aspect
  3. public class MyAspect {
  4. // 用Pointcut注解中的属性来指定对哪些方法进行增强
  5. @Pointcut("@annotation(com.sangeng.aspect.InvokeLog)")
  6. public void pt(){}
  7. /*
  8. 用@Before注解来指定该方法中是增强的代码,并且是在被增强方法执行前执行的
  9. @Before的属性写上加了@Pointcut注解的方法: 方法名()
  10. */
  11. @Before("pt()")
  12. public void methodbefore(){
  13. System.out.println("方法被调用了");
  14. }
  15. }

1.5 通知分类

  • @Before:前置通知,在目标方法执行前执行

  • @AfterReturning: 返回后通知,在目标方法执行后执行,如果出现异常不会执行

  • @After:后置通知,在目标方法之后执行,无论是否出现异常都会执行

  • @AfterThrowing:异常通知,在目标方法抛出异常后执行

  • @Around:环绕通知,围绕着目标方法执行

理解不同通知执行时机。(下面的伪代码是用来理解单个通知的执行时机的,不能用来理解多个通知情况下的执行顺序。如果需要配置多个通知我们会选择使用Around通知,更加的清晰并且好用

  1. public Object test() {
  2. before();//@Before 前置通知
  3. try {
  4. Object ret = 目标方法();//目标方法调用
  5. afterReturing();//@AfterReturning 返回后通知
  6. } catch (Throwable throwable) {
  7. throwable.printStackTrace();
  8. afterThrowing();//@AfterThrowing 异常通知通知
  9. }finally {
  10. after();//@After 后置通知
  11. }
  12. return ret;
  13. }

环绕通知非常特殊,它可以对目标方法进行全方位的增强。

例如:

  1. @Around("pt()")
  2. public void around(ProceedingJoinPoint pjp){
  3. System.out.println("目标方法前");
  4. try {
  5. pjp.proceed();//目标方法执行
  6. System.out.println("目标方法后");
  7. } catch (Throwable throwable) {
  8. throwable.printStackTrace();
  9. System.out.println("目标方法出现异常");
  10. }finally {
  11. System.out.println("finally中进行增强");
  12. }
  13. }

1.6 获取被增强方法相关信息

  1. 我们实际对方法进行增强时往往还需要获取到被增强代码的相关信息,比如方法名,参数,返回值,异常对象等。
  2. 我们可以在除了环绕通知外的所有通知方法中增加一个**JoinPoint类型**的参数。这个参数封装了被增强方法的相关信息。**我们可以通过这个参数获取到除了异常对象和返回值之外的所有信息。**

例如:

  1. @Before("pt()")
  2. public void methodbefore(JoinPoint jp){
  3. Object[] args = jp.getArgs();//方法调用时传入的参数
  4. Object target = jp.getTarget();//被代理对象
  5. MethodSignature signature = (MethodSignature) jp.getSignature();//获取被被增强方法签名封装的对象
  6. System.out.println("Before方法被调用了");
  7. }

案例:

需求:要求让所有service包下类的所有方法被调用前都输出全类名,方法名,以及调用时传入的参数

  1. @Component
  2. @Aspect
  3. public class PrintLogAspect {
  4. //对哪些方法增强
  5. @Pointcut("execution(* com.sangeng.service..*.*(..))")
  6. public void pt(){}
  7. //怎么增强
  8. @Before("pt()")
  9. public void printLog(JoinPoint joinPoint){
  10. //输出 被增强的方法所在的类名 方法名 调用时传入的参数 joinPoint.getSignature().getName() joinPoint.getArgs()
  11. MethodSignature signature = (MethodSignature) joinPoint.getSignature();
  12. //类名
  13. String className = signature.getDeclaringTypeName();
  14. //方法名
  15. String methodName = signature.getName();
  16. //调用时传入的参数
  17. Object[] args = joinPoint.getArgs();
  18. System.out.println(className+"=="+methodName+"======"+ Arrays.toString(args));
  19. }
  20. }
  1. 如果需要**获取被增强方法中的异常对象或者返回值**则需要在方法参数上增加一个对应类型的参数,并且使用注解的属性进行配置。这样Spring会把你想获取的数据赋值给对应的方法参数。

例如:

  1. @AfterReturning(value = "pt()",returning = "ret")//使用returning属性指定了把目标方法返回值赋值给下面方法的参数ret
  2. public void AfterReturning(JoinPoint jp,Object ret){
  3. System.out.println("AfterReturning方法被调用了");
  4. }
  1. @AfterThrowing(value = "pt()",throwing = "t")//使用throwing属性指定了把出现的异常对象赋值给下面方法的参数t
  2. public void AfterThrowing(JoinPoint jp,Throwable t){
  3. System.out.println("AfterReturning方法被调用了");
  4. }
  1. 相信你肯定觉得上面的获取方式特别的麻烦难以理解。就可以使用下面这种万能的方法。
  2. 直接在环绕通知方法中增加一个**ProceedingJoinPoint类型**的参数。这个参数封装了被增强方法的相关信息。

该参数的proceed()方法被调用相当于被增强方法被执行,调用后的返回值就相当于被增强方法的返回值。

例如:

  1. @Around(value = "pt()")
  2. public Object around(ProceedingJoinPoint pjp) {
  3. Object[] args = pjp.getArgs();//方法调用时传入的参数
  4. Object target = pjp.getTarget();//被代理对象
  5. MethodSignature signature = (MethodSignature) pjp.getSignature();//获取被被增强方法签名封装的对象
  6. Object ret = null;
  7. try {
  8. ret = pjp.proceed();//ret就是目标方法执行后的返回值
  9. } catch (Throwable throwable) {
  10. throwable.printStackTrace();//throwable就是出现异常时的异常对象
  11. }
  12. return ret;
  13. }

1.7 AOP应用案例

1.7.1 需求

现有AI核心功能代码如下:

  1. public class AIController {
  2. //AI自动回答
  3. public String getAnswer(String question){
  4. //AI核心代码 价值10个亿
  5. String str = question.replace("吗", "");
  6. str = str.replace("?","!");
  7. return str;
  8. }
  9. //AI算命
  10. public String fortuneTelling(String name){
  11. //AI算命核心代码
  12. String[] strs = {"女犯伤官把夫克,旱地莲花栽不活,不是吃上两家饭,也要刷上三家锅。","一朵鲜花头上戴,一年四季也不开,一心想要花开时,采花之人没到来。","此命生来脾气暴,上来一阵双脚跳,对你脾气啥都好,经常与人吵和闹。"};
  13. int index = name.hashCode() % 3;
  14. return strs[index];
  15. }
  16. }
  1. 现在为了保证数据的安全性,要求调用方法时fortuneTelling传入的姓名是经过加密的。我们需要对传入的参数进行解密后才能使用。并且要对该方法的返回值进行加密后返回。
  2. **PS:后期也可能让其他方法进行相应的加密处理。**

字符串加密解密直接使用下面的工具类即可:

  1. import javax.crypto.Cipher;
  2. import javax.crypto.KeyGenerator;
  3. import javax.crypto.SecretKey;
  4. import javax.crypto.spec.SecretKeySpec;
  5. import java.security.SecureRandom;
  6. public class CryptUtil {
  7. private static final String AES = "AES";
  8. private static int keysizeAES = 128;
  9. private static String charset = "utf-8";
  10. public static String parseByte2HexStr(final byte buf[]) {
  11. final StringBuffer sb = new StringBuffer();
  12. for (int i = 0; i < buf.length; i++) {
  13. String hex = Integer.toHexString(buf[i] & 0xFF);
  14. if (hex.length() == 1) {
  15. hex = '0' + hex;
  16. }
  17. sb.append(hex.toUpperCase());
  18. }
  19. return sb.toString();
  20. }
  21. public static byte[] parseHexStr2Byte(final String hexStr) {
  22. if (hexStr.length() < 1)
  23. return null;
  24. final byte[] result = new byte[hexStr.length() / 2];
  25. for (int i = 0;i< hexStr.length()/2; i++) {
  26. int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
  27. int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
  28. result[i] = (byte) (high * 16 + low);
  29. }
  30. return result;
  31. }
  32. private static String keyGeneratorES(final String res, final String algorithm, final String key, final Integer keysize, final Boolean bEncode) {
  33. try {
  34. final KeyGenerator g = KeyGenerator.getInstance(algorithm);
  35. if (keysize == 0) {
  36. byte[] keyBytes = charset == null ? key.getBytes() : key.getBytes(charset);
  37. g.init(new SecureRandom(keyBytes));
  38. } else if (key == null) {
  39. g.init(keysize);
  40. } else {
  41. byte[] keyBytes = charset == null ? key.getBytes() : key.getBytes(charset);
  42. SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
  43. random.setSeed(keyBytes);
  44. g.init(keysize, random);
  45. }
  46. final SecretKey sk = g.generateKey();
  47. final SecretKeySpec sks = new SecretKeySpec(sk.getEncoded(), algorithm);
  48. final Cipher cipher = Cipher.getInstance(algorithm);
  49. if (bEncode) {
  50. cipher.init(Cipher.ENCRYPT_MODE, sks);
  51. final byte[] resBytes = charset == null? res.getBytes() : res.getBytes(charset);
  52. return parseByte2HexStr(cipher.doFinal(resBytes));
  53. } else {
  54. cipher.init(Cipher.DECRYPT_MODE, sks);
  55. return new String(cipher.doFinal(parseHexStr2Byte(res)));
  56. }
  57. } catch (Exception e) {
  58. e.printStackTrace();
  59. }
  60. return null;
  61. }
  62. public static String AESencode(final String res) {
  63. return keyGeneratorES(res, AES, "aA11*-%", keysizeAES, true);
  64. }
  65. public static String AESdecode(final String res) {
  66. return keyGeneratorES(res, AES, "aA11*-%", keysizeAES, false);
  67. }
  68. public static void main(String[] args) {
  69. System.out.println(
  70. "加密后:" + AESencode("将要加密的明文")
  71. );
  72. System.out.println(
  73. "解密后:" + AESdecode("730CAE52D85B372FB161B39D0A908B8CC6EF6DA2F7D4E595D35402134C3E18AB")
  74. );
  75. }
  76. }

1.7.2 实现

①导入依赖
  1. <!--SpringIOC相关依赖-->
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-context</artifactId>
  5. <version>5.1.9.RELEASE</version>
  6. </dependency>
  7. <!--AOP相关依赖-->
  8. <dependency>
  9. <groupId>org.aspectj</groupId>
  10. <artifactId>aspectjweaver</artifactId>
  11. <version>1.8.13</version>
  12. </dependency>

②开启AOP注解支持
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
  7. <!--配置组件扫描-->
  8. <context:component-scan base-package="com.sangeng"></context:component-scan>
  9. <!--启动AOP注解支持-->
  10. <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
  11. </beans>

③自定义注解

  1. package com.sangeng.aspect;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. @Target(ElementType.METHOD)
  7. @Retention(RetentionPolicy.RUNTIME)
  8. public @interface Crypt {
  9. }

④在目标方法上增加注解

注意:目标对象一定要记得注入Spring容器中

  1. @Controller
  2. public class AIController {
  3. //....
  4. //AI算命
  5. @Crypt
  6. public String fortuneTelling(String name){
  7. System.out.println(name);
  8. //AI算命核心代码
  9. String[] strs = {"女犯伤官把夫克,旱地莲花栽不活,不是吃上两家饭,也要刷上三家锅。","一朵鲜花头上戴,一年四季也不开,一心想要花开时,采花之人没到来。","此命生来脾气暴,上来一阵双脚跳,对你脾气啥都好,经常与人吵和闹。"};
  10. int index = name.hashCode() % 3;
  11. return strs[index];
  12. }
  13. }

⑤定义切面类
  1. package com.sangeng.aspect;
  2. import com.sangeng.util.CryptUtil;
  3. import org.aspectj.lang.ProceedingJoinPoint;
  4. import org.aspectj.lang.annotation.Around;
  5. import org.aspectj.lang.annotation.Aspect;
  6. import org.aspectj.lang.annotation.Pointcut;
  7. import org.springframework.stereotype.Component;
  8. @Component
  9. @Aspect
  10. public class CryptAspect {
  11. //确定切点
  12. @Pointcut("@annotation(com.sangeng.aspect.Crypt)")
  13. public void pt(){
  14. }
  15. //定义通知
  16. @Around("pt()")
  17. public Object crypt(ProceedingJoinPoint pjp) {
  18. //获取去目标方法调用时的参数
  19. Object[] args = pjp.getArgs();
  20. //对参数进行解密 解密后传入目标方法执行
  21. String arg = (String) args[0];
  22. String s = CryptUtil.AESdecode(arg);//解密
  23. args[0] = s;
  24. Object proceed = null;
  25. String ret = null;
  26. try {
  27. proceed = pjp.proceed(args);//目标方法调用
  28. //目标方法执行后需要获取到返回值
  29. ret = (String) proceed;
  30. //对返回值加密后进行真正的返回
  31. ret = CryptUtil.AESencode(ret);
  32. } catch (Throwable throwable) {
  33. throwable.printStackTrace();
  34. }
  35. return ret;
  36. }
  37. }

1.8 xml配置AOP

①定义切面类

  1. public class MyAspect {
  2. public void before(JoinPoint joinPoint){
  3. System.out.println("before");
  4. }
  5. // @AfterReturning(value = "pt()",returning = "ret")
  6. public void afterReturning(JoinPoint joinPoint,Object ret){
  7. System.out.println("afterReturning:"+ret);
  8. }
  9. // @After("pt()")
  10. public void after(JoinPoint joinPoint){
  11. System.out.println("after");
  12. }
  13. // @AfterThrowing(value = "pt()",throwing = "e")
  14. public void afterThrowing(JoinPoint joinPoint,Throwable e){
  15. String message = e.getMessage();
  16. System.out.println("afterThrowing:"+message);
  17. }
  18. public Object around(ProceedingJoinPoint pjp){
  19. //获取参数
  20. Object[] args = pjp.getArgs();
  21. MethodSignature signature = (MethodSignature) pjp.getSignature();
  22. Object target = pjp.getTarget();
  23. Object ret = null;
  24. try {
  25. ret = pjp.proceed();//目标方法的执行
  26. //ret就是被增强方法的返回值
  27. System.out.println(ret);
  28. } catch (Throwable throwable) {
  29. throwable.printStackTrace();
  30. System.out.println(throwable.getMessage());
  31. }
  32. // System.out.println(pjp);
  33. return ret;
  34. }
  35. }

②目标类和切面类注入容器

在切面类和目标类上加是对应的注解。注入如果是使用注解的方式注入容器要记得开启组件扫描。

当然你也可以在xml中使用bean标签的方式注入容器。

  1. @Component//把切面类注入容器
  2. public class MyAspect {
  3. //..。省略无关代码
  4. }
  1. @Service//把目标类注入容器
  2. public class UserService {
  3. //..。省略无关代码
  4. }

③配置AOP

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
  7. <!--开启组件扫描-->
  8. <context:component-scan base-package="com.sangeng"></context:component-scan>
  9. <!--配置AOP-->
  10. <aop:config>
  11. <!--定义切点-->
  12. <aop:pointcut id="pt1" expression="execution(* com.sangeng.service..*.*(..))"></aop:pointcut>
  13. <aop:pointcut id="pt2" expression="@annotation(com.sangeng.aspect.InvokeLog)"></aop:pointcut>
  14. <!--配置切面-->
  15. <aop:aspect ref="myAspect">
  16. <aop:before method="before" pointcut-ref="pt1"></aop:before>
  17. <aop:after method="after" pointcut-ref="pt1"></aop:after>
  18. <aop:after-returning method="afterReturning" pointcut-ref="pt1" returning="ret"></aop:after-returning>
  19. <aop:after-throwing method="afterThrowing" pointcut-ref="pt2" throwing="e"></aop:after-throwing>
  20. </aop:aspect>
  21. </aop:config>
  22. </beans>

1.9 多切面顺序问题

  1. 在实际项目中我们可能会存在配置了多个切面的情况。这种情况下我们很可能需要控制切面的顺序。
  2. 我们在默认情况下Spring有它自己的排序规则。(按照类名排序)
  3. 默认排序规则往往不符合我们的要求,我们需要进行特殊控制。
  4. 如果是注解方式配置的AOP可以在切面类上加**@Order注解**来控制顺序。**@Order中的属性越小优先级越高。**
  5. 如果是XML方式配置的AOP,可以通过调整**配置顺序**来控制。

例如:

下面这种配置方式就会先使用CryptAspect里面的增强,在使用APrintLogAspect里的增强

  1. @Component
  2. @Aspect
  3. @Order(2)
  4. public class APrintLogAspect {
  5. //省略无关代码
  6. }
  7. @Component
  8. @Aspect
  9. @Order(1)
  10. public class CryptAspect {
  11. //省略无关代码
  12. }

1.10 AOP原理-动态代理

  1. 实际上SpringAOP其实底层就是使用动态代理来完成的。并且使用了两种动态代理分别是JDK的动态代理和Cglib动态代理。
  2. 所以我们接下去来学习下这两种动态代理,理解下它们的不同点。

1.10.1 JDK动态代理

  1. JDK的动态代理使用的java.lang.reflect.Proxy这个类来进行实现的。要求被代理(被增强)的类需要实现了接口。并且JDK动态代理也只能对接口中的方法进行增强。
  1. public static void main(String[] args) {
  2. AIControllerImpl aiController = new AIControllerImpl();
  3. //使用动态代理增强getAnswer方法
  4. //1.JDK动态代理
  5. //获取类加载器
  6. ClassLoader cl = Demo.class.getClassLoader();
  7. //被代理类所实现接口的字节码对象数组
  8. Class<?>[] interfaces = AIControllerImpl.class.getInterfaces();
  9. AIController proxy = (AIController) Proxy.newProxyInstance(cl, interfaces, new InvocationHandler() {
  10. //使用代理对象的方法时 会调用到invoke
  11. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  12. //proxy 是代理对象
  13. //method 是当前被调用的方法封装的Method对象
  14. //args 是调用方法时传入的参数
  15. //调用被代理对象的对应方法
  16. //判断 当前调用的是否是getAnswer方法
  17. if(method.getName().equals("getAnswer")){
  18. System.out.println("增强");
  19. }
  20. Object ret = method.invoke(aiController, args);
  21. return ret;
  22. }
  23. });
  24. String answer = proxy.getAnswer("三连了吗?");
  25. System.out.println(answer);
  26. }

1.10.2 Cglib动态代理

  1. 使用的是org.springframework.cglib.proxy.Enhancer类进行实现的。
  1. public class CglibDemo {
  2. public static void main(String[] args) {
  3. Enhancer enhancer = new Enhancer();
  4. //设置父类的字节码对象
  5. enhancer.setSuperclass(AIControllerImpl.class);
  6. enhancer.setCallback(new MethodInterceptor() {
  7. //使用代理对象执行方法是都会调用到intercept方法
  8. @Override
  9. public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
  10. //判断当前调用的方法是不是getAnswer方法 如果是进行增强
  11. if ("getAnswer".equals(method.getName())){
  12. System.out.println("被增强了");
  13. }
  14. //调用父类中对应的方法
  15. Object ret = methodProxy.invokeSuper(o, objects);
  16. return ret;
  17. }
  18. });
  19. //生成代理对象
  20. AIControllerImpl proxy = (AIControllerImpl) enhancer.create();
  21. // System.out.println(proxy.getAnswer("你好吗?"));
  22. System.out.println(proxy.fortuneTelling("你好吗?"));
  23. }
  24. }

1.10.3 总结

  1. JDK动态代理要求被代理(被增强)的类必须要实现接口,生成的代理对象相当于是被代理对象的兄弟。
  2. Cglib的动态代理不要求被代理(被增强)的类要实现接口,生成的代理对象相当于被代理对象的子类对象。
  3. **SpringAOP默认情况下优先使用的是JDK的动态代理,如果使用不了JDK的动态代理才会使用Cglib的动态代理。**

1.11 切换默认动态代理方式

  1. 有的时候我们需要修改AOP的代理方式。
  2. 我们可以使用以下方式修改:

如果我们是采用注解方式配置AOP的话:

设置aop:aspectj-autoproxy标签的proxy-target-class属性为true,代理方式就会修改成Cglib

  1. <aop:aspectj-autoproxy proxy-target-class="true"/>

如果我们是采用xml方式配置AOP的话:

设置aop:config标签的proxy-target-class属性为true,代理方式就会修改成Cglib

  1. <aop:config proxy-target-class="true">
  2. </aop:config>