您的位置:首页 > 编程语言 > Java开发

Spring - AOP

2021-04-04 23:53 1236 查看

[TOC]

AOP

AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。

AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。不通过修改源代码方式,在主干功能里面添加新功能。

官方文档:点我传送

AOP - 概念

  • 连接点: 类里可以被增强的方法称为连接点

  • 切入点: 实际被增强的方法称为切入点

  • 通知(增强):增强的逻辑部分称为通知

    通知类型: 前置通知、后置通知、环绕通知、异常通知、最终通知
  • 切面: 通知应用到切入点的过程称为切面

  • AOP - 原理

    AOP 底层使用动态代理,有两种情况动态代理:

    方式一: JDK动态代理 (有接口情况)
    方式二: CGLIB 动态代理 (没有接口情况)

    JDK动态代理

    • JDK 动态代理,使用 Proxy 类里面的方法创建代理对象。 调用 newProxyInstance 方法

    JDK1.8官方文档:点我传送

    public class Proxy extends Object implements Serializable{
    
    /**
    *   loader:类加载器
    *   interfaces:增强方法所在的类,这个类实现的接口,支持多个接口
    *   InvocationHandler:实现这个接口 InvocationHandler,创建代理对象,写增强的部分
    *
    *   Returns an instance of a proxy class for the specified interfaces that dispatches method invocations to the specified invocation handler.
    */
    static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h);
    }
    • JDK 动态代理代码 创建接口,定义方法
    public interface UserDao {
    public int add(int a,int b);
    public String update(String str);
    }
    • 创建接口实现类,实现方法
    public class UserDaoImpl  implements UserDao {
    @Override
    public int add(int a, int b) {
    return a+b;
    }
    
    @Override
    public String update(String str) {
    return str;
    }
    }
    • 使用 Proxy 类创建接口代理对象
    public class JDKProxy {
    
    public static void main(String[] args) {
    //创建 接口实现类代理对象
    /**
    *      @CallerSensitive
    *     public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h)
    *
    *     public interface InvocationHandler {}
    *
    */
    Class[] interfaces = {UserDao.class};
    UserDaoImpl userDao = new UserDaoImpl();
    UserDao proxyInstance = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
    int result = proxyInstance.add(1, 2);
    String abc = proxyInstance.update("abc");
    }
    }
    
    //创建代理对象代码
    class UserDaoProxy implements InvocationHandler {
    
    //把需要创建的代理对象 传递过来
    private Object obj;
    
    public UserDaoProxy(Object obj) {
    this.obj = obj;
    }
    
    //增强的逻辑(部分)
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
    //方法之前
    System.out.println("方法之前执行: " + method.getName() + " 传递的参数:" + Arrays.toString(args));
    
    //增强的方法执行
    Object invoke = null;
    if (method.getName().equals("add")) {
    System.out.println("UserDaoProxy add ...");
    invoke = method.invoke(obj, args);
    }
    if(method.getName().equals("update")){
    System.out.println("UserDaoProxy update ...");
    invoke = method.invoke(obj, args);
    }
    
    //方法之后
    System.out.println("方法之后执行: " + obj);
    return invoke;
    }
    }

    AOP - 操作

    • Spring 框架一般都是基于 AspectJ 实现 AOP 操作。
    AspectJ 不是 Spring 组成部分,独立 AOP 框架,一般把 AspectJ 和 Spirng 框架一起使用,进行 AOP 操作。

    = 基于 AspectJ 实现 AOP 操作

    - 基于 xml 配置文件实现
    - 基于注解方式实现
    • 引入 AOP 相关依赖
    com.springsource.net.sf.cglib-2.2.0.jar
    com.springsource.org.aopalliance-1.0.0.jar
    com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
    commons-logging-1.1.1.jar
    druid-1.1.9.jar
    spring-aop-5.2.6.RELEASE.jar
    spring-aspects-5.2.6.RELEASE.jar
    spring-beans-5.2.6.RELEASE.jar
    spring-context-5.2.6.RELEASE.jar
    spring-core-5.2.6.RELEASE.jar
    spring-expression-5.2.6.RELEASE.jar

    • 切入点表达式
    # 切入点表达式语法结构: execution([权限修饰符] [返回类型] [类全路径] [方法名称]([参数列表]) )
    
    举例 1:对 com.hosystem.dao.BookDao 类里面的 add 进行增强
    execution(* [返回类型可省略] com.hosystem.dao.BookDao.add(..))
    
    举例 2:对 com.hosystem.dao.BookDao 类里面的所有的方法进行增强
    execution(* com.hosystem.dao.BookDao.* (..))
    
    举例 3:对 com.hosystem.dao 包里面所有类,类里面所有方法进行增强
    execution(* com.hosystem.dao.*.* (..))

    AOP - AspectJ-注解

    • 创建类

    User.java

    public class User {
    
    public void add(){
    System.out.println("User add ...");
    }
    }

    UserProxy.java

    //增强类
    public class UserProxy {
    //前置通知
    public void before(){
    System.out.println("UserProxy before ... ");
    }
    }
    • 进行通知的配置

    在 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.hosystem.spring5.dao.aopannotation"></context:component-scan>
    </beans>

    使用注解创建 User 和 UserProxy 对象

    //增强类
    @Component
    public class UserProxy {...}
    
    @Component
    public class User {...}

    增强类上面添加注解 @Aspect

    //增强类
    @Component
    @Aspect //生成代理对象
    public class UserProxy {
    //前置通知
    public void before(){
    System.out.println("UserProxy before ... ");
    }
    }

    在 spring 配置文件中开启生成代理对象

    <!--    开启Aspect生成代理对象-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    • 配置不同类型的通知

    在增强类的里面,在作为通知方法上面添加通知类型注解,使用切入点表达式配置

    //增强类
    @Component
    @Aspect //生成代理对象
    public class UserProxy {
    
    //前置通知
    //@Before注解表示作为前置通知
    @Before(value = "execution(* com.hosystem.spring5.dao.aopannotation.User.add(..))")
    public void before() {
    System.out.println("UserProxy before ... ");
    }
    
    //最终通知
    @After(value = "execution(* com.hosystem.spring5.dao.aopannotation.User.add(..))")
    public void after() {
    System.out.println("UserProxy after ... ");
    }
    
    //后置通知(返回通知)
    @AfterReturning(value = "execution(* com.hosystem.spring5.dao.aopannotation.User.add(..))")
    public void afterReturning() {
    System.out.println("UserProxy afterReturning ... ");
    }
    
    //异常通知
    @AfterThrowing(value = "execution(* com.hosystem.spring5.dao.aopannotation.User.add(..))")
    public void afterThrowing() {
    System.out.println("UserProxy afterThrowing ... ");
    }
    
    //环绕通知
    //public interface ProceedingJoinPoint extends JoinPoint{}
    @Around(value = "execution(* com.hosystem.spring5.dao.aopannotation.User.add(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
    System.out.println("UserProxy aroud 环绕之前... ");
    
    //被增强的方法执行
    proceedingJoinPoint.proceed();
    
    System.out.println("UserProxy aroud 环绕之后... ");
    }
    }
    • 相同切入点抽取
    //增强类
    @Component
    @Aspect //生成代理对象
    public class UserProxy {
    
    //相同切入点抽取
    @Pointcut(value = "execution(* com.hosystem.spring5.dao.aopannotation.User.add(..))")
    public void pointdemo(){}
    
    //前置通知
    //@Before注解表示作为前置通知
    @Before(value = "pointdemo()")
    public void before() {
    System.out.println("UserProxy before ... ");
    }
    }
    • 测试
    public class TestAop {
    
    /**
    * 正常执行流程:
    * UserProxy aroud 环绕之前...
    * UserProxy before ...
    * User add ...
    * UserProxy aroud 环绕之后...
    * UserProxy after ...
    * UserProxy afterReturning ...
    *
    *  有error错误流程:
    * UserProxy aroud 环绕之前...
    * UserProxy before ...
    * UserProxy after ...
    * UserProxy afterThrowing ...
    */
    @Test
    public void testAopAnno(){
    ApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("bean1.xml");
    User user = classPathXmlApplicationContext.getBean("user", User.class);
    user.add();
    }
    }

    • 增强类优先级

    有多个增强类多同一个方法进行增强,设置增强类优先级。

    在增强类上面添加注解 @Order(数字类型值),数字类型值越小优先级越高

    @Aspect
    @Component
    @Order(1)
    public class PersonProxy {
    
    //后置通知(返回通知)
    @Before(value = "execution(* com.hosystem.spring5.dao.aopannotation.User.add(..))")
    public void before() {
    System.out.println("PersonProxy before ... ");
    }
    }
    • 注解开发

    创建配置类,不需要创建 xml 配置文件

    @Configuration
    @ComponentScan(basePackages = {"com.hosystem"})
    @EnableAspectJAutoProxy(proxyTargetClass = true) //<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    public class ConfigAop {
    }

    AOP - AspectJ-Xml文件

    • 创建类

    创建两个类,增强类和被增强类,创建方法

    Book.java

    public class Book {
    public void buy(){
    System.out.println("book buy ...");
    }
    }

    BookProxy.java

    public class BookProxy {
    public void befor(){
    System.out.println("BookProxy before ...");
    }
    }
    • xml配置文件
    <!--    创建对象-->
    <bean id="book" class="com.hosystem.spring5.dao.aopxml.Book"></bean>
    <bean id="bookProxy" class="com.hosystem.spring5.dao.aopxml.BookProxy"></bean>
    
    <!--    配置aop增强-->
    <aop:config>
    <!--        切入点-->
    <aop:pointcut id="pcut" expression="execution(* com.hosystem.spring5.dao.aopxml.Book.buy(..))"/>
    <!--        配置切面-->
    <aop:aspect ref="bookProxy">
    <!--            增强作用在具体的方法上-->
    <aop:before method="before" pointcut-ref="pcut"></aop:before>
    </aop:aspect>
    </aop:config>
    内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
    标签: