zoukankan      html  css  js  c++  java
  • 第4章 面向切面的Spring

    4.1 什么是面向切面编程

    AOP(Aspect Oriented Programming),即面向切面编程,可以说是OOP(Object Oriented Programming,面向对象编程)的补充和完善。OOP引入封装、继承、多态等概念来建立一种对象层次结构,用于模拟公共行为的一个集合。不过OOP允许开发者定义纵向的关系,但并不适合定义横向的关系,例如日志功能。日志代码往往横向地散布在所有对象层次中,而与它对应的对象的核心功能毫无关系对于其他类型的代码,如安全性、异常处理和透明的持续性也都是如此,这种散布在各处的无关的代码被称为横切(cross cutting),在OOP设计中,它导致了大量代码的重复,而不利于各个模块的重用。

    AOP技术恰恰相反,它利用一种称为"横切"的技术,剖解开封装的对象内部,并将那些影响了多个类的公共行为封装到一个可重用模块,并将其命名为"Aspect",即切面。所谓"切面",简单说就是那些与业务无关,却为业务模块所共同调用的逻辑或责任封装起来,便于减少系统的重复代码,降低模块之间的耦合度,并有利于未来的可操作性和可维护性。

    使用"横切"技术,AOP把软件系统分为两个部分:核心关注点横切关注点。业务处理的主要流程是核心关注点,与之关系不大的部分是横切关注点。横切关注点的一个特点是,他们经常发生在核心关注点的多处,而各处基本相似,比如权限认证、日志、事物。AOP的作用在于分离系统中的各种关注点,将核心关注点和横切关注点分离开来。

    AOP核心概念

    1、横切关注点

    对哪些方法进行拦截,拦截后怎么处理,这些关注点称之为横切关注点

    2、切面(aspect)

    类是对物体特征的抽象,切面就是对横切关注点的抽象

    3、连接点(joinpoint)

    被拦截到的点,因为Spring只支持方法类型的连接点,所以在Spring中连接点指的就是被拦截到的方法,实际上连接点还可以是字段或者构造器

    4、切入点(pointcut)

    对连接点进行拦截的定义

    5、通知(advice)

    所谓通知指的就是指拦截到连接点之后要执行的代码,通知分为前置、后置、异常、最终、环绕通知五类

    6、目标对象

    代理的目标对象

    7、织入(weave)

    将切面应用到目标对象并导致代理对象创建的过程

    8、引入(introduction)

    在不修改代码的前提下,引入可以在运行期为类动态地添加一些方法或字段

    4.2 通过切点来选择连接点

    请注意我们使用了 “&&” 操作符把 execution() 和 within() 指示器连接在一起形成与( and )关系(切点必须匹配所有的指示器)。类似地,我们可以使用 “||” 操作符来标识或( or )关系,而使用 “!” 操作符来标识非( not )操作。 因为 “&” 在 XML 中有特殊含义,所以在 Spring 的 XML 配置里面描述切点时,我们可以使用 and 来代替 “&&” 。同样, or 和 not 可以分别用来代替 “||” 和 “!” 。

    除了表 4.1 所列的指示器外, Spring 还引入了一个新的 bean() 指示器,它允许我们在切点表达式中使用 bean 的 ID 来标识 bean 。 bean() 使用bean ID 或 bean 名称作为参数来限制切点只匹配特定的 bean 。

    4.3 使用注解创建切面

    定义切面

    Audience.java

    package ch04.aspect;
    ​
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.*;
    import org.springframework.stereotype.Component;
    ​
    @Aspect
    @Component
    public class Audience {
        @Pointcut(value = "execution(* ch04.service.Performance.perform(int)) && args(num)")
        public void performance2(int num){
    ​
        }
        @Pointcut(value = "execution(* ch04.service.Performance.perform(int)) && args(num)")
        public void performance(int num){
    ​
        }
        @Before("performance(num)")
        public void silenceCellPhones(int num){
            System.out.println("Silencing cell phones , "+ num);
        }
    //    @Before("performance()")
    //    public void takeSeats(){
    //        System.out.println("Taking seats");
    //    }
    //    @AfterReturning("performance()")
    //    public void applause(){
    //        System.out.println("CLAP CLAP CLAP!!!");
    //    }
    //    @AfterThrowing("performance()")
    //    public void demandRefund(){
    //        System.out.println("Demanding a refund");
    //    }
        @Around("performance2(num)")
        public void watchPerformance(ProceedingJoinPoint joinPoint , int num){
            try{
                System.out.println("Silencing cell phones ," + num);
                System.out.println("Taking seats");
                joinPoint.proceed();
                System.out.println("CLAP CLAP CLAP!!!");
            }catch (Throwable e){
                System.out.println("Demanding a refund");
            }
        }
    }
    ​

    注意:在 Audience 中, performance() 方法使用了 @Pointcut 注解。为 @Pointcut 注解设置的值是一个切点表达式,就像之前在通知注解上所设置的那样。通过在 performance() 方法上添加 @Pointcut 注解,我们实际上扩展了切点表达式语言,这样就可以在任何的切点表达式中使用 performance() 了,如果不这样做的话,你需要在这些地方使用那个更长的切点表达式。我们现在把所有通知注解中的长表达式都替换成了 performance() 。

    如果你使用 JavaConfig 的话,可以在配置类的类级别上通过使用 EnableAspectJ-AutoProxy 注解启用自动代理功能。程序清单 4.3 展现了如何在 JavaConfig 中启用自动代理。假如你在 Spring 中要使用 XML 来装配 bean 的话,那么需要使用 Spring aop 命名空间中的 <aop:aspectj-autoproxy> 元素。下面的 XML 配置展现了如何完成该功能。

    RootConfig.java

    package ch04.config;
    ​
    import ch04.Main;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.EnableAspectJAutoProxy;
    ​
    @Configuration
    @EnableAspectJAutoProxy
    @ComponentScan(basePackages = {"ch04.service","ch04.aspect"})
    public class RootConfig {
    ​
        @Bean
        public Main main(){
            return new Main();
        }
    }
    ​

    不管你是使用 JavaConfig 还是 XML , AspectJ 自动代理都会为使用 @Aspect 注解的 bean 创建一个代理,这个代理会围绕着所有该切面的切点所匹配的 bean 。

    创建环绕通知

    环绕通知是最为强大的通知类型。它能够让你所编写的逻辑将被通知的目标方法完全包装起来。实际上就像在一个通知方法中同时编写前置通知和后置通知。

    @Around("performance2(num)")
    public void watchPerformance(ProceedingJoinPoint joinPoint , int num){
        try{
            System.out.println("Silencing cell phones ," + num);
            System.out.println("Taking seats");
            joinPoint.proceed();
            System.out.println("CLAP CLAP CLAP!!!");
        }catch (Throwable e){
            System.out.println("Demanding a refund");
        }
    }

    需要注意的是,别忘记调用 proceed() 方法。如果不调这个方法的话,那么你的通知实际上会阻塞对被通知方法的调用。有可能这就是你想要的效果,但更多的情况是你希望在某个点上执行被通知的方法。

    处理通知中的参数

     
    @Pointcut(value = "execution(* ch04.service.Performance.perform(int)) && args(num)")
    public void performance2(int num){
    ​
    }
    @Before("performance(num)")
    public void silenceCellPhones(int num){
        System.out.println("Silencing cell phones , "+ num);
    }

    通过注解引入新的功能

     

    EncoreableIntroducer.java

    package ch04.aspect;
    ​
    import ch04.service.Encoreable;
    import ch04.service.impl.DefaultEncoreable;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.DeclareParents;
    import org.springframework.stereotype.Component;
    ​
    @Aspect
    @Component
    public class EncoreableIntroducer {
        @DeclareParents(value = "ch04.service.Performance+",defaultImpl = DefaultEncoreable.class)
        public static Encoreable encoreable;
    }

    Encoreable.java

    package ch04.service;
    ​
    public interface Encoreable {
        void performEncore();
    }

    使用

    @Autowired
    Performance performance;
    ​
    public void run(){
        performance.perform(2);
        ((Encoreable)performance).performEncore();
    }

    @DeclareParents 注解由三部分组成:

    • value 属性指定了哪种类型的 bean 要引入该接口。在本例中,也就是所有实现 Performance 的类型。(标记符后面的加号表示是 Performance 的所有子类型,而不是 Performance 本身。)

    • defaultImpl 属性指定了为引入功能提供实现的类。在这里,我们指定的是 DefaultEncoreable 提供实现。

    • @DeclareParents 注解所标注的静态属性指明了要引入了接口。在这里,我们所引入的是 Encoreable 接口。

    4.4 在xml中生命切面

    在 Spring 的 aop 命名空间中,提供了多个元素用来在 XML 中声明切面,如表 4.3 所示。

    我们已经看过了 <aop:aspectj-autoproxy> 元素,它能够自动代理 AspectJ 注解的通知类。 aop 命名空间的其他元素能够让我们直接在Spring 配置中声明切面,而不需要使用注解。

    声明前置和后置通知  

    声明环绕通知

    为通知传递参数

    通过切面引入新的功能

    delegate-ref 属性引用了一个 Spring bean 作为引入的委托。这需要在 Spring 上下文中存在一个 ID 为 encoreableDelegate 的 bean 。

    4.5 注入AspectJ切面

    精心设计且有意义的切面很可能依赖其他类来完成它们的工作。如果在执行通知时,切面依赖于一个或多个类,我们可以在切面内部实例化这些协作的对象。但更好的方式是,我们可以借助 Spring 的依赖注入把 bean 装配进 AspectJ 切面中。

  • 相关阅读:
    (初学者)安装hadoop集群注意事项
    配置HADOOP_HOME
    修改用户所在组,修改文件的所有者,明明是自己的文件什么不能解压?
    方法被阻塞,一直要等到线程任务返回结果的例子
    Python复习笔记(一)高级变量类型
    我的vim插件配置
    vim使用笔记
    Linux命令(九)查找文件find
    Linux命令(八)Linux系统信息相关命令
    Linux命令(七)Linux用户管理和修改文件权限
  • 原文地址:https://www.cnblogs.com/xuzhen97/p/9287378.html
Copyright © 2011-2022 走看看