Spring 学习总结 (3)--- AOP原理、AOP的实现方式

1. AOP原理

1.1 什么是AOP

AOP(Aspect Oriented Programming):面向切面编程,是OOP的延续。

可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术。AOP实际是GoF设计模式的延续,设计模式孜孜不倦追求的是调用者和被调用者之间的解耦,AOP可以说也是这种目标的一种实现。

我们现在做的一些非业务,如:日志、事务、安全等都会写在业务代码中(也即是说,这些非业务类横切于业务类),但这些代码往往是重复,复制——粘贴式的代码会给程序的维护带来不便,AOP就实现了把这些业务需求与系统需求分开来做。这种解决的方式也称代理机制
在这里插入图片描述
在这里插入图片描述
AOP的本质是动态代理

1.2 AOP的术语

AOP的概念图:

在这里插入图片描述

横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 …

切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。

通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。

目标(Target):被通知对象。

代理(Proxy):向目标对象应用通知之后创建的对象。

切入点(PointCut):切面通知 执行的 “地点”的定义。

连接点(JointPoint):与切入点匹配的执行点。

SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:

通知类型连接点实现接口
前置通知方法前org.springframework.aop.MethodBeforeAdvice
后置通知方法后org.springframework.aop.AfterReturningAdvice
环绕通知方法前后org.aopalliance.intercept.MethodInterceptor
异常抛出通知方法抛出异常org.springframework.aop.ThrowsAdivce
引介通知类中增加新的方法属性org.springframework.aop.IntroductionInterceptor

Aop很重要:一定要理解其中思路,主要要思想这一块,横向编程

1.3 AOP在Spring中的作用

AOP在Spring中的作用:

  • 提供声明式事务;
  • 允许用户自定义切面

2. AOP的实现方式

2.1 使用SpringAPI实现AOP

Spring的AOP就是将公共业务代码(日志,事务,安全…),和业务类(真实对象)结合起来,实现公共业务的重复利用,以实现解耦的功能。

  • 编写业务类 接口

    package org.xiao.service;
    
    // 业务类   接口
    public interface UserService {
         void add();
         void delete();
         void updata();
         void query();
    }
    
  • 实现类

    package org.xiao.service;
    
    public class UserServerImpl implements UserService {
    
        public void add() {
            System.out.println("增加用户");
        }
    
        public void delete() {
            System.out.println("删除用户");
        }
    
        public void updata() {
            System.out.println("更新用户");
        }
    
        public void query() {
            System.out.println("查询用户信息");
        }
    }
    
  • 定义日志增加类实现

    前置通知:

    package org.xiao.log;
    
    import org.springframework.aop.MethodBeforeAdvice;
    
    import java.lang.reflect.Method;
    
    //前向通知 实现 MethodBeforeAdvice 前置通知接口
    public class BeforeLog implements MethodBeforeAdvice {
    
        //重写其 before 方法
        //method: 要执行的目标对象的方法
        //objects: 要被调用的方法的参数
        //o:目标对象
        public void before(Method method, Object[] objects, Object o) throws Throwable {
            System.out.println("前置通知:执行了"+o.getClass().getName()+"的"+method.getName()+"方法");
        }
    }
    

    后置通知:

    package org.xiao.log;
    
    import org.springframework.aop.AfterReturningAdvice;
    
    import java.lang.reflect.Method;
    
    //后置通知  实现AfterReturningAdvice 接口
    public class AfterLog implements AfterReturningAdvice {
        //重写afterReturning 方法
        public void afterReturning(Object returnValue, Method method, Object[] objects, Object o) throws Throwable {
            //returnValue : 返回值
            //method : 被调用的方法
            //objects : 被调用的方法对象的参数
            //o: 被调用的目标对象
            System.out.println("后置通知:执行了"+o.getClass().getName()+"的"+method.getName()+"方法,"
            +"返回值为"+returnValue);
        }
    }
    
  • 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: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/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd">
    
        <!--注册bean-->
        <bean id="userService" class="org.xiao.service.UserServerImpl"/>
    
        <!--注册日志类的bean-->
        <bean id="beforeLog" class="org.xiao.log.BeforeLog"/>
        <bean id="afterLog" class="org.xiao.log.AfterLog"/>
    
    
        <!--使用spring的aop切入
        1.导入约束:
            xmlns:aop="http://www.springframework.org/schema/aop"
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
        2.语法:aop:config
        -->
        <aop:config>
            <!--切入点
            expression 表达式,表示要切入的位置
            语法:execution([类的修饰符] [类的全路径] [方法] [参数])
            -->
            <aop:pointcut id="pointcut"
                          expression="execution(* org.xiao.service.UserServerImpl.*(..))"/>
    
            <!--执行通知,增强-->
            <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
            <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
        </aop:config>
    
    </beans>
    
  • 导包

    需要导入aop的织入包:

    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.9</version>
    </dependency>
    
  • 测试类

    package org.xiao.service;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class AOPTest {
        @Test
        public void test(){
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
            UserService userService = (UserService) applicationContext.getBean("userService");
    
            userService.delete();
        }
    }
    
  • 测试结果
    在这里插入图片描述

2.2 自定义类实现AOP

  • 真实对象 和之前的一样

  • 自定义一个Aop增强类,即切面

    package org.xiao.diy;
    
    
    //自定义的Aop增强类,即切面
    public class Diy {
    
        public void before(){
            System.out.println("方法执行前");
        }
    
        public void after(){
            System.out.println("方法执行后");
        }
    }
    
  • Spring核心配置文件

     <!--注册bean-->
    <bean id="userService" class="org.xiao.service.UserServerImpl"/>
    
    <!--注册自定义的AOP增强类-->
    <bean id="diy" class="org.xiao.diy.Diy"/>
    
    <!--编写aop配置文件-->
    <aop:config>
         <!--切面-->
         <aop:aspect ref="diy">
             <!--切入点-->
             <aop:pointcut id="diyPointCut" expression="execution(* org.xiao.service.UserServerImpl.*(..))"/>
             <aop:before method="before" pointcut-ref="diyPointCut"/>
             <aop:after method="after" pointcut-ref="diyPointCut"/>
         </aop:aspect>
    </aop:config>    
    
  • 测试结果
    在这里插入图片描述

2.3 使用注解实现AOP

@before @after

  • 目标对象不变

  • 增强的类,写注解

    • 需要将类注解为切面
    • 方法上就是切入点,增强
    package org.xiao.anno;
    
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.After;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.aspectj.lang.annotation.Around;
    
    
    //切面注解   必须写,否则无法切入
    @Aspect
    public class Anno {
        //切入点   可以直接写到增强上面
        @Before("execution(* org.xiao.service.UserServerImpl.*(..))")
        public void before() {
            System.out.println("---方法执行前----");
        }
    
        @After("execution(* org.xiao.service.UserServerImpl.*(..))")
        public void after() {
            System.out.println("----方法执行后----");
        }
    
        //环绕增加
        //切入点参数 : ProceedingJoinPoint
        //环绕增强本质:
        /*
        将目标对象作为参数传递进方法中,
        在方法执行的前后,增加一些操作,仅此而已
        但是可以拿到一些目标对象的东西;
         */
        @Around("execution(* org.xiao.service.UserServerImpl.*(..))")
        public void around(ProceedingJoinPoint joinPoint) throws Throwable {
            System.out.println("环绕增强前");
            System.out.println("执行切入点" + joinPoint.getStaticPart());  //获得切入点
    
            //执行目标方法
            Object proceed = joinPoint.proceed();
    
            System.out.println("环绕增强后");
            System.out.println(proceed);  //null
        }
    }
    
  • 配置文件

     <!--注册bean-->
    <bean id="userService" class="org.xiao.service.UserServerImpl"/>
    
    <!--注解实现AOP的类-->
    <bean id="anno" class="org.xiao.anno.Anno"/>
    
    <!--识别注解,自动代理-->
    <aop:aspectj-autoproxy/>
    
  • 测试结果
    在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值