[019-15].第14节:面向切面编程AOP

我的后端学习大纲

我Spring学习大纲


1.AOP介绍:

1.1.AOP概述:

  • 1.IOC使软件组件松耦合。AOP可以实现捕捉系统中经常使用的功能,把它转化成组件
  • 2.AOP(Aspect Oriented Programming):
    • AOP是对OOP的补充延伸,AOP是一种编程技术
    • AOP就是面向切面编程,面向方面编程
      • 我们把一些公共的,通用的,重复的功能称为切面,面向切面编程就是将切面提取出来,单独开发,转换为组件,然后我们在需要调用的方法中,通过动态代理的方式进行织入.
      • 利用 AOP的思想可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。 通俗描述:不通过修改源代码方式,在主干功能里面添加新功能
    • AOP底层使用的就是动态代理来实现的
  • 3.Spring的AOP使用的动态代理是:JDK动态代理 + CGLIB动态代理技术
    • Spring在这两种动态代理中灵活切换,如果是代理接口,会默认使用JDK动态代理,
    • 如果要代理某个类,这个类没有实现接口,就会切换使用CGLIB。当然,也可以强制通过一些配置让Spring只使用CGLIB。

1.2.案例理解AOP:

a.系统权限功能加强:

  • 1.在登录时,有很多系统需要添加权限的判断,那么就可以把权限模块单独抽出来开发作为一个组件进行使用:
    在这里插入图片描述

b.日志、事务管理、安全等功能加强:

  • 1.一般一个系统当中都会有一些系统服务,例如:日志、事务管理、安全等。这些系统服务被称为:交叉业务,这些交叉业务几乎是通用的,不管你是做银行账户转账,还是删除用户数据。日志、事务管理、安全,这些都是需要做的。如果在每一个业务处理过程当中,都掺杂这些交叉业务代码进去的话,存在两方面问题:
    • 第一:交叉业务代码在多个业务流程中反复出现,显然这个交叉业务代码没有得到复用。并且修改这些交叉业务代码的话,需要修改多处。
    • 第二:程序员无法专注核心业务代码的编写,在编写核心业务代码的同时还需要处理这些交叉业务。
  • 2.使用AOP可以很轻松的解决以上问题。

在这里插入图片描述

总结AOP:将与核心业务无关的代码独立的抽取出来,形成一个独立的组件,然后以横向交叉的方式应用到业务流程当中的过程被称为AOP


1.3.AOP的优点:

  • 1.代码复用性增强。
  • 2.代码易维护。
  • 3.使开发者更关注业务逻辑。

2.AOP中的一些术语及其操作:

2.1.重要术语:

  • 1.连接点Joinpoint:
    • 在程序的整个执行流程中,可以织入切面的位置。方法的执行前后,异常抛出之后等位置,连接点描述的是位置
  • 2.切点 Pointcut:
    • 在程序执行流程中,真正织入切面的方法(一个切点对应多个连接点)。切点描述的是方法
  • 3.通知(增强)Advice:
    • 通知又叫增强,就是具体你要织入的代码
    • 通知包括:
      • 前置通知
      • 后置通知
      • 环绕通知
      • 异常通知
      • 最终通知
  • 4.切面 Aspect
    • 切点 + 通知就是切面,就是具体的增强动作
  • 5.织入 Weaving:
    • 把通知应用到目标对象上的过程
  • 6.代理对象 Proxy:
    • 一个目标对象被织入通知后产生的新对象
  • 7.目标对象 Target:
    • 被织入通知的对象
      在这里插入图片描述

2.2.切点表达式:

a.切入点表达式是干啥的:

  • 1.切入点表达式作用:知道对哪个类里面的哪个方法进行增强,是用来定义通知(Advice)往哪些方法上切入

b.语法结构:

execution([权限修饰符] [返回类型] [类全路径] [方法名称]([参数列表]) [异常])

  • 1.访问控制权限修饰符:
    • 可选项。
    • 没写,就是4个权限都包括。
    • 写public就表示只包括公开的方法。
  • 2.返回值类型:
    • 必填项
    • * 表示返回值类型任意
  • 3.全限定类名:
    • 可选项。
    • 两个点“..”代表当前包以及子包下的所有类
    • 省略时表示所有的类
  • 4.方法名:
    • 必填项
    • *表示所有方法
    • set*表示所有的set方法
  • 5.形式参数列表:
    • 必填项
    • () 表示没有参数的方法
    • (..) 参数类型和个数随意的方法
    • (*) 只有一个参数的方法
    • (*, String) 第一个参数类型随意,第二个参数是String的。
  • 6.异常:
    • 可选项。
    • 省略时表示任意异常类型。

c.理解以下的切点表达式::

//举例 1:
//对 com.atguigu.dao.BookDao 类里面的 add 进行增强																																																																													
execution(* com.atguigu.dao.BookDao.add(..))括号里面的*表示是:对所有权限修饰都成立。

//举例 2:
//对 com.atguigu.dao.BookDao 类里面的所有的方法进行增强
execution(* com.atguigu.dao.BookDao.* (..))

//举例 3:
//对 com.atguigu.dao 包里面所有类,类里面所有方法进行增强
execution(* com.atguigu.dao.*.* (..))

//service包下所有的类中以delete开始的所有方法
execution(public * com.powernode.mall.service.*.delete*(..))

//mall包下所有的类的所有的方法
execution(* com.powernode.mall..*(..))

//所有类的所有方法
execution(* *(..))

2.3.使用Spring的AOP:

a.Spring对AOP的实现包括以下2种方式:

  • 1.第一种方式:Spring框架结合AspectJ框架实现的AOP,基于注解方式
  • 2.第二种方式:Spring框架结合AspectJ框架实现的AOP,基于XML方式

b.什么是AspectJ:

  • 1.AspectJ是Eclipse组织的一个支持AOP的框架。AspectJ框架是独立于Spring框架之外的一个框架,Spring框架用了AspectJ
  • 2.AspectJ项目起源于帕洛阿尔托(Palo Alto)研究中心(缩写为PARC)。该中心由Xerox集团资助,Gregor Kiczales领导,从1997年开始致力于AspectJ的开发,1998年第一次发布给外部用户,2001年发布1.0 release。因为AspectJ的发展和受关注程度大大超出了PARC的预期,PARC在2003年3月正式将AspectJ项目移交给了Eclipse组织

c.编码使用Spring+AspectJ实现AOP

c1.准备工作
  • 1.在项目工程里面引入 AOP 相关依赖:引入的依赖列表如下图
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.powernode</groupId>
    <artifactId>spring6-010-spring-aspectj-aop-anno</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <!--仓库-->
    <repositories>
        <!--spring里程碑版本的仓库-->
        <repository>
            <id>repository.spring.milestone</id>
            <name>Spring Milestone Repository</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>

    <!--依赖-->
    <dependencies>
        <!--spring context-->
        <!--spring aop依赖,不需要手动引入,因为引入上面的context依赖后,aop依赖自动引入了-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>6.0.0-M2</version>
        </dependency>
        <!--spring aspects-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>6.0.0-M2</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

</project>
  • 2.Spring配置文件中添加context命名空间和aop命名空间
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

</beans>
c2.AspectJ 注解方式实现AOP
c2-1.编码实现:
  • 1.定义目标类以及目标方法(需要被增强的类和方法
package com.powernode.spring6.service;
// 目标类
public class OrderService {
    // 目标方法
    public void generate(){
        System.out.println("订单已生成!");
    }
}
  • 2.定义切面类(切点 + 通知就是切面,就是具体的增强动作
package com.powernode.spring6.service;
import org.aspectj.lang.annotation.Aspect;
// 切面类
@Aspect
public class MyAspect {

}
  • 3.目标类和切面类都纳入spring bean管理:
    • 在目标类OrderService上添加@Component注解。
    • 在切面类MyAspect类上添加@Component注解。
  • 4.在spring配置文件中添加组建扫描
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--开启组件扫描-->
    <context:component-scan base-package="com.powernode.spring6.service"/>
</beans>
  • 5.在切面类中添加通知
package com.powernode.spring6.service;

import org.springframework.stereotype.Component;
import org.aspectj.lang.annotation.Aspect;

// 切面类
@Aspect
@Component
public class MyAspect {
    // 这就是需要增强的代码(通知)
    public void advice(){
        System.out.println("我是一个通知");
    }
}

  • 6.在通知上添加切点表达式(通知+切点=切面),注解@Before表示前置通知。
package com.powernode.spring6.service;

import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.aspectj.lang.annotation.Aspect;

// 切面类
@Aspect
@Component
public class MyAspect {
    // 切点表达式
    @Before("execution(* com.powernode.spring6.service.OrderService.*(..))")
    // 这就是需要增强的代码(通知)
    public void advice(){
        System.out.println("我是一个通知");
    }
}
  • 7.在spring配置文件中启用自动代理
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--开启组件扫描-->
    <context:component-scan base-package="com.powernode.spring6.service"/>
    <!--开启自动代理-->
    <aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>
  • <aop:aspectj-autoproxy proxy-target-class="true"/> 开启自动代理之后,凡事带有@Aspect注解的bean都会生成代理对象。
    • proxy-target-class="true" 表示采用cglib动态代理。
    • proxy-target-class="false" 表示采用jdk动态代理。默认值是false。即使写成false,当没有接口的时候,也会自动选择cglib生成代理类。
  • 8.测试:
package com.powernode.spring6.test;

import com.powernode.spring6.service.OrderService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AOPTest {
    @Test
    public void testAOP(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-aspectj-aop-annotation.xml");
        OrderService orderService = applicationContext.getBean("orderService", OrderService.class);
        orderService.generate();
    }
}
  • 9.测试结果
我是一个通知
订单已生成
c2-2.通知类型:
  • 前置通知:@Before 目标方法执行之前的通知
  • 后置通知:@AfterReturning 目标方法执行之后的通知
  • 环绕通知:@Around 目标方法之前添加通知,同时目标方法执行之后添加通知
  • 异常通知:@AfterThrowing 发生异常之后执行的通知
  • 最终通知:@After 放在finally语句块中的通知
  • 1.在增强类中配置其他不同类型的通知,在增强类的里面,在作为通知方法的上面添加通知类型注解,使用切入点表达式配置
package com.powernode.spring6.service;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

// 切面类
@Component
@Aspect
public class MyAspect {

    @Around("execution(* com.powernode.spring6.service.OrderService.*(..))")
    public void aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕通知开始");
        // 执行目标方法。
        proceedingJoinPoint.proceed();
        System.out.println("环绕通知结束");
    }

    @Before("execution(* com.powernode.spring6.service.OrderService.*(..))")
    public void beforeAdvice(){
        System.out.println("前置通知");
    }

    @AfterReturning("execution(* com.powernode.spring6.service.OrderService.*(..))")
    public void afterReturningAdvice(){
        System.out.println("后置通知");
    }

    @AfterThrowing("execution(* com.powernode.spring6.service.OrderService.*(..))")
    public void afterThrowingAdvice(){
        System.out.println("异常通知");
    }

    @After("execution(* com.powernode.spring6.service.OrderService.*(..))")
    public void afterAdvice(){
        System.out.println("最终通知");
    }

}
  • 2.目标类和目标方法
package com.powernode.spring6.service;

import org.springframework.stereotype.Component;

// 目标类
@Component
public class OrderService {
    // 目标方法
    public void generate(){
        System.out.println("订单已生成!");
    }
}

  • 3.测试程序:
package com.powernode.spring6.test;

import com.powernode.spring6.service.OrderService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AOPTest {
    @Test
    public void testAOP(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-aspectj-aop-annotation.xml");
        OrderService orderService = applicationContext.getBean("orderService", OrderService.class);
        orderService.generate();
    }
}
  • 4.执行结果:
    在这里插入图片描述
c2-3.注意细节:

1.可以在各个通知类型中抽取相同的切入点

//相同切入点抽取,
//在增强类找中,随便定义个方法,进行如下定义
@Pointcut(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
public void pointdemo() {
}

//前置通知
//@Before 注解表示作为前置通知
@Before(value = "pointdemo()")
public void before() {
  System.out.println("before.........");
}

2.我们知道,业务流程当中不一定只有一个切面,可能有的切面控制事务,有的记录日志,有的进行安全控制,如果有多个增强类对同一个方法进行增强时,可以设置增强类的优先级 ;在增强类上面添加注解 @Order(数字类型值),数字类型值越小优先级越高

package com.atguigu.spring5.aopanno;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Order(1)
public class PersonProxy {
    //后置通知(返回通知)
    @Before(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void afterReturning() {
        System.out.println("Person Before.........");
    }
}

3.优化使用切点表达式:

  • 1.以下代码中表达式的缺点:
    • 第一:切点表达式重复写了多次,没有得到复用。
    • 第二:如果要修改切点表达式,需要修改多处,难维护。
package com.powernode.spring6.service;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

// 切面类
@Component
@Aspect
@Order(2)
public class MyAspect {

    @Around("execution(* com.powernode.spring6.service.OrderService.*(..))")
    public void aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕通知开始");
        // 执行目标方法。
        proceedingJoinPoint.proceed();
        System.out.println("环绕通知结束");
    }

    @Before("execution(* com.powernode.spring6.service.OrderService.*(..))")
    public void beforeAdvice(){
        System.out.println("前置通知");
    }

    @AfterReturning("execution(* com.powernode.spring6.service.OrderService.*(..))")
    public void afterReturningAdvice(){
        System.out.println("后置通知");
    }

    @AfterThrowing("execution(* com.powernode.spring6.service.OrderService.*(..))")
    public void afterThrowingAdvice(){
        System.out.println("异常通知");
    }

    @After("execution(* com.powernode.spring6.service.OrderService.*(..))")
    public void afterAdvice(){
        System.out.println("最终通知");
    }

}

  • 2.改善:将切点表达式单独的定义出来,在需要的位置引入即可。如下:
package com.powernode.spring6.service;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

// 切面类
@Component
@Aspect
@Order(2)
public class MyAspect {
    
    @Pointcut("execution(* com.powernode.spring6.service.OrderService.*(..))")
    public void pointcut(){}

    @Around("pointcut()")
    public void aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕通知开始");
        // 执行目标方法。
        proceedingJoinPoint.proceed();
        System.out.println("环绕通知结束");
    }

    @Before("pointcut()")
    public void beforeAdvice(){
        System.out.println("前置通知");
    }

    @AfterReturning("pointcut()")
    public void afterReturningAdvice(){
        System.out.println("后置通知");
    }

    @AfterThrowing("pointcut()")
    public void afterThrowingAdvice(){
        System.out.println("异常通知");
    }

    @After("pointcut()")
    public void afterAdvice(){
        System.out.println("最终通知");
    }

}

使用@Pointcut注解来定义独立的切点表达式
注意这个@Pointcut注解标注的方法随意,只是起到一个能够让@Pointcut注解编写的位置。

c2-4.连接点说明:
  • 1.无论是前置、后置、环绕、最终通知等,都有JoinPoint这个类型的参数,通过这个参数,可以获取到目标方法的一些基本信息
    在这里插入图片描述
c2-5.使用全注解式开发AOP

全注解开发AOP就是:就是编写一个类,在这个类上面使用大量注解来代替spring的配置文件,spring配置文件消失了

  • 1.创建配置类,不需要创建任何的xml 配置文件
package com.powernode.spring6.service;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan("com.powernode.spring6.service")
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class Spring6Configuration {

}
  • 2.测试:
@Test
public void testAOPWithAllAnnotation(){
    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Spring6Configuration.class);
    OrderService orderService = applicationContext.getBean("orderService", OrderService.class);
    orderService.generate();
}

c3.AspectJ基于XML文件方式实现AOP:
  • 1.编写目标类(不添加@Component注解):
package com.powernode.spring6.service;

// 目标类
public class VipService {
    public void add(){
        System.out.println("保存vip信息。");
    }
}
  • 2.编写切面类,并且编写通知(不添加@Component注解
package com.powernode.spring6.service;

import org.aspectj.lang.ProceedingJoinPoint;

// 负责计时的切面类
public class TimerAspect {
    
    public void time(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long begin = System.currentTimeMillis();
        //执行目标
        proceedingJoinPoint.proceed();
        long end = System.currentTimeMillis();
        System.out.println("耗时"+(end - begin)+"毫秒");
    }
}

  • 2.在 spring 配置文件中创建两个类(Book类和BookProxy 类)的对象
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--纳入spring bean管理-->
    <bean id="vipService" class="com.powernode.spring6.service.VipService"/>
    <bean id="timerAspect" class="com.powernode.spring6.service.TimerAspect"/>

    <!--aop配置-->
    <aop:config>
        <!--切点表达式-->
        <aop:pointcut id="p" expression="execution(* com.powernode.spring6.service.VipService.*(..))"/>
        <!--切面-->
        <aop:aspect ref="timerAspect">
            <!--切面=通知 + 切点-->
            <aop:around method="time" pointcut-ref="p"/>
        </aop:aspect>
    </aop:config>
</beans>
  • 4.测试是否成功
package com.powernode.spring6.test;

import com.powernode.spring6.service.VipService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AOPTest3 {

    @Test
    public void testAOPXml(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-aop-xml.xml");
        VipService vipService = applicationContext.getBean("vipService", VipService.class);
        vipService.add();
    }
}


3.AOP的底层原理 :

在AOP底层使用的是动态代理:

  • 第一种 有接口情况,使用 JDK 动态代理
  • 第二种 没有接口情况,使用 CGLIB 动态代理

3.1.使用JDK动态代理情况:

  • 1.现在想把实现类中的login()方法进行增强:
    • 现在有UserDao接口,使用这个接口的话就必须得有实现类 (UserDaoImpl),然后在这个实现类中实现login()方法。
    • 现在所谓的增强登录这个方法,就比如说在登录的时候,加上一个权限判断。这个时候就可以使用JDK的动态代理原理来增强。
  • 2.增强方法就是:再创建个UserDao接口的实现类(这是个整体,一块读,是说的接口实现类)的一个代理对象(使用Proxy类里面的方法来创建代理对象,具体创建方式见3.1),再通过代理对象 进行login方法的增强。
    在这里插入图片描述

3.2.使用CGLIB动态代理情况

a.增强User类中的add()方法

  • 传统就是可以再创建个子类,继承User类,然后再改写add方法。
  • 动态代理的方式就是:创建当前类子类的代理对象。增强add方法。
    在这里插入图片描述

3.3.AOP两种动态代理实现方式的举例:

a.使用JDK动态代理情况:

a1.使用JDK动态代理,使用Proxy类里面的方法创建代理对象;JDK8在线说明文档

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 调用Proxy类中的newProxyInstance(ClassLoader loader, 类<?>[] interfaces, InvocationHandler h)方法。这个方法一共有有三个参数
    • 第一个参数:类加载器
package com.atguigu.spring5;

public interface UserDao {
    public int add(int a,int b);
    public String update(String id);
}
  • 第二个参数:增强方法所在 的类,这个实现类的接口,支持多个接口
package com.atguigu.spring5;
public class UserDaoImpl implements UserDao {
    @Override
    public int add(int a, int b) {
        System.out.println("add方法执行了.....");
        return a+b;
    }
    @Override
    public String update(String id) {
        System.out.println("update方法执行了.....");
        return id;
    }
}

  • 第三个参数: 实现这个接口InvocatrionHandler,创建代理对象,写增强方法
package com.atguigu.spring5;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
@SuppressWarnings("all")
public class JDKProxy {

    public static void main(String[] args) {
        //创建接口实现类代理对象
        Class[] interfaces = {UserDao.class};
        UserDaoImpl userDao = new UserDaoImpl();
        UserDao dao = (UserDao)Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        int result = dao.add(1, 2);
        System.out.println("result:"+result);
    }
}
//创建代理对象代码
class UserDaoProxy implements InvocationHandler {
    /**
     * 1 创建的是谁的代理对象,就把谁传递过来;这里是创建的UserDaoImpl的代理对象,所以就把UserDaoImpl传过来。
     *  通过有参构造来进行传递
     * */
    private Object obj;
    public UserDaoProxy(Object obj) {
        this.obj = obj;
    }
    /**
     * 在invoke方法中书写 增强的逻辑
     * */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //方法之前
        System.out.println("方法之前执行...."+method.getName()+" :传递的参数..."+ Arrays.toString(args));
        //被增强的方法执行
        Object res = method.invoke(obj, args);
        //方法之后
        System.out.println("方法之后执行...."+obj);
        return res;
    }
}
  • 执行结果:
    在这里插入图片描述

4.AOP的实际案例:

4.1.事务处理:

a.概述:

  • 1.项目中的事务控制是在所难免的。在一个业务流程当中,可能需要多条DML语句共同完成,为了保证数据的安全,这多条DML语句要么同时成功,要么同时失败。这就需要添加事务控制的代码。

b.举例:

  • 1.代码如下:
class 业务类1{
    public void 业务方法1(){
        try{
            // 开启事务
            startTransaction();
            
            // 执行核心业务逻辑
            step1();
            step2();
            step3();
            ....
            
            // 提交事务
            commitTransaction();
        }catch(Exception e){
            // 回滚事务
            rollbackTransaction();
        }
    }
    public void 业务方法2(){
        try{
            // 开启事务
            startTransaction();
            
            // 执行核心业务逻辑
            step1();
            step2();
            step3();
            ....
            
            // 提交事务
            commitTransaction();
        }catch(Exception e){
            // 回滚事务
            rollbackTransaction();
        }
    }
    public void 业务方法3(){
        try{
            // 开启事务
            startTransaction();
            
            // 执行核心业务逻辑
            step1();
            step2();
            step3();
            ....
            
            // 提交事务
            commitTransaction();
        }catch(Exception e){
            // 回滚事务
            rollbackTransaction();
        }
    }
}

class 业务类2{
    public void 业务方法1(){
        try{
            // 开启事务
            startTransaction();
            
            // 执行核心业务逻辑
            step1();
            step2();
            step3();
            ....
            
            // 提交事务
            commitTransaction();
        }catch(Exception e){
            // 回滚事务
            rollbackTransaction();
        }
    }
    public void 业务方法2(){
        try{
            // 开启事务
            startTransaction();
            
            // 执行核心业务逻辑
            step1();
            step2();
            step3();
            ....
            
            // 提交事务
            commitTransaction();
        }catch(Exception e){
            // 回滚事务
            rollbackTransaction();
        }
    }
    public void 业务方法3(){
        try{
            // 开启事务
            startTransaction();
            
            // 执行核心业务逻辑
            step1();
            step2();
            step3();
            ....
            
            // 提交事务
            commitTransaction();
        }catch(Exception e){
            // 回滚事务
            rollbackTransaction();
        }
    }
}
//......
  • 2.可以看到,这些业务类中的每一个业务方法都是需要控制事务的,而控制事务的代码又是固定的格式,都是:
try{
    // 开启事务
    startTransaction();

    // 执行核心业务逻辑
    //......

    // 提交事务
    commitTransaction();
}catch(Exception e){
    // 回滚事务
    rollbackTransaction();
}

这个控制事务的代码就是和业务逻辑没有关系的“交叉业务”。以上伪代码当中可以看到这些交叉业务的代码没有得到复用,并且如果这些交叉业务代码需要修改,那必然需要修改多处,难维护,怎么解决?可以采用AOP思想解决。可以把以上控制事务的代码作为环绕通知,切入到目标类的方法当中。接下来我们做一下这件事,有两个业务类,如下:

c.改善:

  • 1.银行账户的业务类:
package com.powernode.spring6.biz;

import org.springframework.stereotype.Component;

@Component
// 业务类
public class AccountService {
    // 转账业务方法
    public void transfer(){
        System.out.println("正在进行银行账户转账");
    }
    // 取款业务方法
    public void withdraw(){
        System.out.println("正在进行取款操作");
    }
}

  • 2.订单业务类
package com.powernode.spring6.biz;

import org.springframework.stereotype.Component;

@Component
// 业务类
public class OrderService {
    // 生成订单
    public void generate(){
        System.out.println("正在生成订单");
    }
    // 取消订单
    public void cancel(){
        System.out.println("正在取消订单");
    }
}

注意,以上两个业务类已经纳入spring bean的管理,因为都添加了@Component注解。接下来我们给以上两个业务类的4个方法添加事务控制代码,使用AOP来完成:

  • 3.事务切面类:
    • 这个事务控制代码只需要写一次就行了,并且修改起来也没有成本。
package com.powernode.spring6.biz;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
// 事务切面类
public class TransactionAspect {
    
    @Around("execution(* com.powernode.spring6.biz..*(..))")
    public void aroundAdvice(ProceedingJoinPoint proceedingJoinPoint){
        try {
            System.out.println("开启事务");
            // 执行目标
            proceedingJoinPoint.proceed();
            System.out.println("提交事务");
        } catch (Throwable e) {
            System.out.println("回滚事务");
        }
    }
}

  • 4.编写测试程序:
package com.powernode.spring6.test;

import com.powernode.spring6.biz.AccountService;
import com.powernode.spring6.biz.OrderService;
import com.powernode.spring6.service.Spring6Configuration;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AOPTest2 {
    @Test
    public void testTransaction(){
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Spring6Configuration.class);
        OrderService orderService = applicationContext.getBean("orderService", OrderService.class);
        AccountService accountService = applicationContext.getBean("accountService", AccountService.class);
        // 生成订单
        orderService.generate();
        // 取消订单
        orderService.cancel();
        // 转账
        accountService.transfer();
        // 取款
        accountService.withdraw();
    }
}
  • 5.执行结果:通过测试可以看到,所有的业务方法都添加了事务控制的代码。
    在这里插入图片描述

4.2.安全日志

a.需求:

  • 1.项目开发结束了,已经上线了。运行正常。客户提出了新的需求:凡事在系统中进行修改操作的,删除操作的,新增操作的,都要把这个人记录下来。因为这几个操作是属于危险行为。例如有业务类和业务方法:

b.编码:

package com.powernode.spring6.biz;

import org.springframework.stereotype.Component;

@Component
//用户业务
public class UserService {
    public void getUser(){
        System.out.println("获取用户信息");
    }
    public void saveUser(){
        System.out.println("保存用户");
    }
    public void deleteUser(){
        System.out.println("删除用户");
    }
    public void modifyUser(){
        System.out.println("修改用户");
    }
}
  • 2.商品业务类:
package com.powernode.spring6.biz;

import org.springframework.stereotype.Component;

// 商品业务类
@Component
public class ProductService {
    public void getProduct(){
        System.out.println("获取商品信息");
    }
    public void saveProduct(){
        System.out.println("保存商品");
    }
    public void deleteProduct(){
        System.out.println("删除商品");
    }
    public void modifyProduct(){
        System.out.println("修改商品");
    }
}

注意:已经添加了@Component注解。接下来我们使用aop来解决上面的需求:编写一个负责安全的切面类

  • 3.负责安全的切面类:
package com.powernode.spring6.biz;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class SecurityAspect {

    @Pointcut("execution(* com.powernode.spring6.biz..save*(..))")
    public void savePointcut(){}

    @Pointcut("execution(* com.powernode.spring6.biz..delete*(..))")
    public void deletePointcut(){}

    @Pointcut("execution(* com.powernode.spring6.biz..modify*(..))")
    public void modifyPointcut(){}

    @Before("savePointcut() || deletePointcut() || modifyPointcut()")
    public void beforeAdivce(JoinPoint joinpoint){
        System.out.println("XXX操作员正在操作"+joinpoint.getSignature().getName()+"方法");
    }
}

  • 4.测试程序
@Test
public void testSecurity(){
    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Spring6Configuration.class);
    UserService userService = applicationContext.getBean("userService", UserService.class);
    ProductService productService = applicationContext.getBean("productService", ProductService.class);
    userService.getUser();
    userService.saveUser();
    userService.deleteUser();
    userService.modifyUser();
    productService.getProduct();
    productService.saveProduct();
    productService.deleteProduct();
    productService.modifyProduct();
}
  • 5.执行结果:
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值