• AOP面向切面编程


    面向切面编程AOP

    概述

    IoC使软件组件松耦合。AOP让你能够捕捉系统中经常使用的功能,把它转化成组件。

    AOP(Aspect Oriented Programming):面向切面编程,面向方面编程。(AOP是一种编程技术 , 是基于OOP基础之上新的编程思想)

    Spring的AOP的底层使用的动态代理:JDK动态代理 + CGLIB动态代理技术 , Spring在这两种动态代理中灵活切换

    • 如果是代理接口,会默认使用JDK动态代理
    • 如果要代理某个类,这个类没有实现接口,就会切换使用CGLIB
    • 当然,你也可以强制通过一些配置让Spring只使用CGLIB

    AOP思想

    一般一个系统当中都会有一些系统服务,例如:日志、事务管理、安全等。这些系统服务被称为:交叉业务(非业务逻辑代码)

    • 这些交叉业务几乎是通用的,不管你是做银行账户转账,还是删除用户数据。日志、事务管理、安全,这些都是需要做的。

    **如果在每一个业务处理过程当中,都掺杂这些交叉业务代码进去的话,存在两方面问题 ** , 使用AOP可以很轻松的解决以上问题

    • 第一:交叉业务代码在多个业务流程中反复出现,显然这个交叉业务代码没有得到复用。并且修改这些交叉业务代码的话,需要修改多处
    • 第二:程序员无法专注核心业务代码的编写,在编写核心业务代码的同时还需要处理这些交叉业务

    AOP的思想

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

    img

    AOP的优点

    • 第一:代码复用性增强。
    • 第二:代码易维护。
    • 第三:使开发者更关注业务逻辑。

    AOP的七大术语

    public class UserService{
        public void do1(){
            System.out.println("do 1");
        }
        public void do2(){
            System.out.println("do 2");
        }
        public void do3(){
            System.out.println("do 3");
        }
        public void do4(){
            System.out.println("do 4");
        }
        public void do5(){
            System.out.println("do 5");
        }
        // 核心业务方法
        public void service(){
            try{
                //连接点 Joinpoint
                do1();//切点  Pointcut
                //连接点 Joinpoint
                do2();//切点  Pointcut
                //连接点 Joinpoint
                do3();//切点  Pointcut
                //连接点 Joinpoint
                do5();//切点  Pointcut
                //连接点 Joinpoint
            }
            catch(Exception e){
                //连接点 Joinpoint
            }finally{}
            	//连接点 Joinpoint
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    连接点 Joinpoint: 在程序的整个执行流程中,可以织入切面的位置。方法的执行前后,异常抛出之后等位置。(连接点描述的是位置)

    • 在程序的整个执行流程中,可以织入切面的位置。方法的执行前后,异常抛出之后等位置。
    • 在程序的整个执行流程中,可以织入切面的位置。方法的执行前后,异常抛出之后等位置。

    **切点 Pointcut: **在程序执行流程中,真正织入切面的方法。一个切点对应多个连接点 (切点本质就是方法)

    通知 Advice: 通知又叫增强包括五种,就是具体你要织入的增强代码 , 例如事务代码 , 日志代码 , 安全代码。(通知描述的增强的代码 , 以方法的形式出现)

    • 前置通知 : 增强代码放在在目标方法之前的连接点上的通知
    • 后置通知:增强代码放在在目标方法之后的连接点上的通知
    • 环绕通知:增强代码既放在目标方法前又放在目标方法后的连接点上的通知
    • 异常通知:在目标方法抛出异常之后 , 放在catch语句块中的连接点的通知
    • 最终通知: 放在finally语句块中的连接点的通知

    切面 Aspect: 切点 + 通知就是切面。

    **织入 Weaving:**把通知应用到目标对象上的过程。

    代理对象 Proxy: 一个目标对象被织入通知后产生的新对象。

    **目标对象 Target: **被织入通知的对象。

    img

    切点表达式

    切点表达式用来定义通知(Advice)往哪些方法上切入。就是根据你指定的规则去匹配方法

    切入点表达式语法格式:execution([访问控制权限修饰符] 返回值类型 [全限定类名]方法名(形式参数列表) [异常])

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

    通配符

    *

    • 在全类名中的字符串中一个 * 可以匹配一个或者多个字符
    • 在包的路径中一个 * 只能匹配一层路径
    • 在形参列表和返回值类型中 , 一个 * 匹配任意一个参数类型
    • 在访问修饰符中不能使用 * , 如果不写默认匹配的是public修饰符

    • 在形参列表中匹配任意数量、任意类型的参数
    • 在包所在的路径中能匹配任意多层路径

    ==“&&”、“||”、“!” ,==连接多个切入点表达式

    • && 表示我们要切入的位置满足这两个切点表达式
    • || 表示我们要切入的位置满足任意一个切点表达式即可
    • ! 表示我们要切入的位置只要不是这个切点表达式都行

    理解以下的切点表达式

    //service包下所有的类中以delete开始的所有方法
    execution(public * com.powernode.mall.service.*.delete*(..))
        
    //mall包下所有的类的所有的方法
    execution(* com.powernode.mall..*(..))   
        
    // 所有类的所有方法
    execution(* *(..))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    使用Spring的AOP

    实现方式

    Spring对AOP的实现包括以下3种方式

    • 第一种方式(常用):Spring框架结合AspectJ框架实现的AOP,基于注解方式。
    • 第二种方式(常用):Spring框架结合AspectJ框架实现的AOP,基于XML方式。
    • 第三种方式(了解):Spring框架自己实现的AOP,基于XML配置方式。

    **AspectJ是Eclipse组织的一个支持AOP的框架。AspectJ框架是独立于Spring框架之外的一个框架,Spring框架用了AspectJ **

    • AspectJ项目起源于帕洛阿尔托(Palo Alto)研究中心(缩写为PARC)。该中心由Xerox集团资助,Gregor Kiczales领导,从1997年开始致力于AspectJ的开发,1998年第一次发布给外部用户,2001年发布1.0 release。
    • 为了推动AspectJ技术和社团的发展,PARC在2003年3月正式将AspectJ项目移交给了Eclipse组织,因为AspectJ的发展和受关注程度大大超出了PARC的预期,他们已经无力继续维持它的发展。

    准备工作

    使用Spring+AspectJ的AOP需要引入的依赖如下

    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>6.0.0-M2version>
    dependency>
    
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-aopartifactId>
      <version>6.0.0-M2version>
    dependency>
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-aspectsartifactId>
      <version>6.0.0-M2version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    Spring配置文件中添加context命名空间和aop命名空间

    
    <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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    基于AspectJ的AOP注解式开发

    第一步:定义目标类以及目标方法

    • 没有写接口 , 底层一定会使用CGLIB的动态代理
    // 目标类
    public class OrderService {
        // 目标方法
        public void generate(){
            System.out.println("订单已生成!");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    第二步:定义切面类 ,(指定通知方法切入的位置)

    • 使用@Aspect注解告诉Spring到底哪个是切面类
    • 使用通知注解告诉Spring通知方法切入的位置1
    // 切面类
    @Aspect
    public class MyAspect {
    }
    
    • 1
    • 2
    • 3
    • 4

    第三步:目标类和切面类都纳入spring bean管理

    • 在目标类OrderService上添加**@Component**注解。
    • 在切面类MyAspect类上添加**@Component**注解。

    第四步:在spring配置文件中添加组建扫描

    • 开启组件扫描模式: context 名称空间
    • 开启基于注解的AOP模式 : AOP名称空间
    
    <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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    第五步:在切面类中添加通知 , 并在通知上添加切点表达式

    • 注解@Before表示前置通知
    // 切面类
    @Aspect
    @Component
    public class MyAspect {
        
        // 切点表达式
        @Before("execution(* com.powernode.spring6.service.OrderService.*(..))")
        // 这就是需要增强的代码(通知)
        public void advice(){
            System.out.println("我是一个通知");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    第六步:在spring配置文件中启用自动代理

    • spring容器在扫描类的时候,查看该类上是否有@Aspect注解,如果有,则给这个类生成代理对象
    • proxy-target-class=“true” 表示强制使用cglib动态代理。
    • proxy-target-class=“false” 表示使用jdk动态代理。默认值是false。即使写成false,当没有接口的时候,也会自动选择cglib生成代理类。
    
    <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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    测试程序

    img

    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();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    通知类型及其执行顺序

    前置通知:@Before 目标方法执行之前的通知

    后置通知:@AfterReturning 目标方法执行之后的通知

    环绕通知:@Around 目标方法之前添加通知,同时目标方法执行之后添加通知 , 在中间需要执行目标方法。

    • 执行目标方法时需要一个ProceedingJoinPoint 类型的参数连接点 , 调用连接点的 proceed() 来执行目标方法 , 这个连接点在Spring调用这个方法的时候会自动传过来
    • 环绕通知(环绕是最大的通知,在前置通知之前,在后置通知之后。)

    异常通知:@AfterThrowing 发生异常之后执行的通知

    最终通知:@After 放在finally语句块中的通知

    注意: 其他通知的连接点都是 JoinPoint 类型的 , 在Spring容器调用这个方法的时候自动传过来

    // joinPoint.getSignature()表示获取目标方法的签名。通过方法的签名可以获取到一个方法的具体信息。
    // 通过签名获取目标方法的方法名。
    System.out.println("目标方法的方法名:" + joinPoint.getSignature().getName());
    
    • 1
    • 2
    • 3

    定义目标类及目标方法(没有抛出异常)

    // 目标类
    @Component
    public class OrderService {
        // 目标方法
        public void generate(){
            System.out.println("订单已生成!");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    **定义切面类 **

    // 切面类
    @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("最终通知");
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    测试程序

    img

    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();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    目标类的目标方法发生异常

    • 当发生异常之后,最终通知也会执行,因为最终通知@After会出现在finally语句块中。出现异常之后,后置通知环绕通知的结束部分不会执行。

    img

    // 目标类
    @Component
    public class OrderService {
        // 目标方法
        public void generate(){
            System.out.println("订单已生成!");
            if (1 == 1) {
                throw new RuntimeException("模拟异常发生");
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    切面的先后顺序

    我们知道,业务流程当中不一定只有一个切面,可能有的切面控制事务,有的记录日志,有的进行安全控制,如果多个切面的话,顺序如何控制

    • 可以使用@Order注解来标识切面类,为@Order注解的value指定一个整数型的数字,数字越小,优先级越高

    再定义一个切面类YourAspect , 并设置优先级

    @Aspect
    @Component
    @Order(1) //设置优先级
    public class YourAspect {
    
        @Around("execution(* com.powernode.spring6.service.OrderService.*(..))")
        public void aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
            System.out.println("YourAspect环绕通知开始");
            // 执行目标方法。
            proceedingJoinPoint.proceed();
            System.out.println("YourAspect环绕通知结束");
        }
    
        @Before("execution(* com.powernode.spring6.service.OrderService.*(..))")
        public void beforeAdvice(){
            System.out.println("YourAspect前置通知");
        }
    
        @AfterReturning("execution(* com.powernode.spring6.service.OrderService.*(..))")
        public void afterReturningAdvice(){
            System.out.println("YourAspect后置通知");
        }
    
        @AfterThrowing("execution(* com.powernode.spring6.service.OrderService.*(..))")
        public void afterThrowingAdvice(){
            System.out.println("YourAspect异常通知");
        }
    
        @After("execution(* com.powernode.spring6.service.OrderService.*(..))")
        public void afterAdvice(){
            System.out.println("YourAspect最终通知");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    设置切面类MyAspect的优先级

    // 切面类
    @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("最终通知");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    YourAspect的优先级高

    img

    MyAspect的优先级高

    img

    抽取可重用的切点表达式

    随便声明一个没有实现的返回void的空方法 , 方法名随意 , 方法体中也不需要写任何代码, 这个方法只是起到一个能够让@Pointcut注解编写的位置的作用

    • 在其他通知方法使用方法名引入切点表达式 , , 切点表达式得到复用 , 实现改一处即改所有

    注意: 在本类中可以直接使用通用切点表达式的方法名 , 如果跨类使用需要补全通用表达式前面的全限定类名

    // 切面类
    @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("最终通知");
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    AOP的实际案例

    编程式事务处理

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

    • 可以看到,这些业务类中的每一个业务方法都是需要控制事务的,而控制事务的代码又是固定的格式 这个控制事务的代码就是和业务逻辑没有关系的“交叉业务”。
    • 交叉业务的代码没有得到复用,并且如果这些交叉业务代码需要修改,那必然需要修改多处,难维护,
    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();
            }
        }
    }
    
    class 业务类2{
        public void 业务方法1(){
            try{
                // 开启事务
                startTransaction();
                
                // 执行核心业务逻辑
                step1();
                step2();
                step3();
                ....
                
                // 提交事务
                commitTransaction();
            }catch(Exception e){
                // 回滚事务
                rollbackTransaction();
            }
        }
    }
    //......
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62

    可以采用AOP思想解决。可以把以上控制事务的代码作为环绕通知,切入到目标类的方法当中 , 定义两个业务类

    @Component
    // 业务类
    public class AccountService {
        // 转账业务方法
        public void transfer(){
            System.out.println("正在进行银行账户转账");
        }
        // 取款业务方法
        public void withdraw(){
            System.out.println("正在进行取款操作");
        }
    }
    
    
    @Component
    // 业务类
    public class OrderService {
        // 生成订单
        public void generate(){
            System.out.println("正在生成订单");
        }
        // 取消订单
        public void cancel(){
            System.out.println("正在取消订单");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    使用AOP来完成给以上两个业务类的4个方法添加事务控制代码到一个事务切面类中

    • 这个事务控制代码是不是只需要写一次就行了,并且修改起来也没有成本
    @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("回滚事务");
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    
    
        
        
        
        
        
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    编写测试程序可以看到,所有的业务方法都添加了事务控制的代码。

    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();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    img

    安全日志

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

    定义业务类和业务方法

    @Service
    //用户业务
    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("修改用户");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    // 商品业务类
    @Service
    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("修改商品");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    接下来我们使用AOP来解决上面的需求:编写一个负责安全的切面类

    @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()+"方法");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    @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();
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    img

  • 相关阅读:
    CAD如何转PDF?接下来分享这三个方法和操作步骤给你
    11. Revit API UI 补充
    力扣 -- 516. 最长回文子序列
    Andriod学习笔记(二)
    Linux(基于Centos7)(二)
    【Kubernetes | Pod 系列】Pod 的基本管理(2)——对 Pod 的查询
    【笔记】电商RFM模型
    入职环境安装经验
    c++入门必学库函数 sort
    关于文件选择器 input type=file原生样式的优化
  • 原文地址:https://blog.csdn.net/qq_57005976/article/details/133286015