Spring核心 面向切面 AOP

在软件开发中,散布于应用中多处的功能被称为横切关注点(crosscutting concern)。一般来说,这些横切关注点从概念上是与应用的业务逻辑相分离的(可是每每会直接嵌入到应用的业务逻辑之中)。把这些横切关注点与业务逻辑相分离正是面向切面编程(AOP)所要解决的问题java

面向切面编程

下图展示了一个被划分为模块的典型应用。每一个模块的核心功能都是为特定业务领域提供服务,可是这些模块都须要相似的辅助功能,例如安全和事务管理正则表达式

图片描述

切面提供了取代继承和委托的方案,且在不少场景下更清晰简洁。使用面向切面编程时,仍然在一个地方定义通用功能,可是能够经过声明的方式定义这个功能要以何种方式在何处应用,而无需修改受影响的类。横切关注点能够被模块化为特殊的类,这些类被称为切面(aspect)spring

这样作有两个好处:首先,如今每一个关注点都集中于一个地方,而不是分散到多处代码中;其次,服务模块更简洁,由于它们只包含主要关注点(或核心功能)的代码,而次要关注点的代码被转移到切面中编程

定义AOP术语

描述切面的经常使用术语有通知(advice)、切点(pointcut)和链接点(join point)。下图展现了这些概念的关联方式安全

图片描述

通知(Advice)

切面的工做被称为通知。通知定义了切面是什么以及什么时候使用app

Spring切面能够应用5种类型的通知:框架

  • 前置通知(Before):在目标方法被调用以前调用通知功能dom

  • 后置通知(After):在目标方法完成以后调用通知,此时不会关心方法的输出是什么模块化

  • 返回通知(After-returning):在目标方法成功执行以后调用通知工具

  • 异常通知(After-throwing):在目标方法抛出异常后调用通知

  • 环绕通知(Around):通知包裹了被通知的方法,在被通知的方法调用以前和调用以后执行自定义的行为

链接点(Join point)

链接点是在应用执行过程当中可以插入切面的一个点。这个点能够是调用方法时、抛出异常时、甚至修改一个字段时。切面代码能够利用这些点插入到应用的正常流程之中,并添加新的行为

切点(Poincut)

通知定义了切面的“什么”和“什么时候”的话,切点定义了“何处”。切点的定义会匹配通知所要织入的一个或多个链接点

一般使用明确的类和方法名称,或是利用正则表达式定义所匹配的类和方法名称来指定这些切点。有些AOP框架容许建立动态的切点,能够根据运行时的决策(好比方法的参数值)来决定是否应用通知

切面(Aspect)

切面是通知和切点的结合。通知和切点共同定义了切面的所有内容——它是什么,在什么时候和何处完成其功能

引入(Introduction)

引入容许咱们向现有的类添加新方法或属性。例如,咱们能够建立一个Auditable通知类,该类记录了对象最后一次修改时的状态。这很简单,只需一个方法,setLastModified(Date),和一个实例变量来保存这个状态。而后,这个新方法和实例变量就能够被引入到现有的类中,从而能够在无需修改这些现有的类的状况下,让它们具备新的行为和状态

织入(Weaving)

织入是把切面应用到目标对象并建立新的代理对象的过程。切面在指定的链接点被织入到目标对象中。在目标对象的生命周期里有多个点能够进行织入:

  • 编译期:切面在目标类编译时被织入。这种方式须要特殊的编译器。AspectJ的织入编译器就是以这种方式织入切面的

  • 类加载期:切面在目标类加载到JVM时被织入。这种方式须要特殊的类加载器(ClassLoader),它能够在目标类被引入应用以前加强该目标类的字节码。AspectJ 5的加载时织入(load-time weaving,LTW)就支持以这种方式织入切面

  • 运行期:切面在应用运行的某个时刻被织入。通常状况下,在织入切面时,AOP容器会为目标对象动态地建立一个代理对象。Spring AOP就是以这种方式织入切面的

Spring对AOP的支持

Spring提供了4种类型的AOP支持:

  • 基于代理的经典Spring AOP

  • 纯POJO切面

  • @AspectJ注解驱动的切面

  • 注入式AspectJ切面(适用于Spring各版本)

Spring通知是Java编写的

Spring所建立的通知都是用标准的Java类编写的。并且,定义通知所应用的切点一般会使用注解或在Spring配置文件里采用XML来编写

AspectJ与之相反。虽然AspectJ如今支持基于注解的切面,但AspectJ最初是以Java语言扩展的方式实现的。这种方式有优势也有缺点。经过特有的AOP语言,咱们能够得到更强大和细粒度的控制,以及更丰富的AOP工具集,可是咱们须要额外学习新的工具和语法

Spring在运行时通知对象

经过在代理类中包裹切面,Spring在运行期把切面织入到Spring管理的bean中。如图所示,代理类封装了目标类,并拦截被通知方法的调用,再把调用转发给真正的目标bean。当代理拦截到方法调用时,在调用目标bean方法以前,会执行切面逻辑

图片描述
Spring的切面由包裹了目标对象的代理类实现。代理类处理方法的调用,执行额外的切面逻辑,并调用目标方法

直到应用须要被代理的bean时,Spring才建立代理对象。若是使用的是ApplicationContext的话,在ApplicationContext从BeanFactory中加载全部bean的时候,Spring才会建立被代理的对象。由于Spring运行时才建立代理对象,因此咱们不须要特殊的编译器来织入Spring AOP的切面

Spring只支持方法级别的链接点

经过使用各类AOP方案能够支持多种链接点模型。由于Spring基于动态代理,因此Spring只支持方法链接点。Spring缺乏对字段链接点的支持,没法让咱们建立细粒度的通知,例如拦截对象字段的修改。并且它不支持构造器链接点,咱们就没法在bean建立时应用通知。可是方法拦截能够知足绝大部分的需求。若是须要方法拦截以外的链接点拦截功能,那么能够利用Aspect来补充Spring AOP的功能

经过切点来选择链接点

关于Spring AOP的AspectJ切点,Spring仅支持AspectJ切点指示器(pointcut designator)的一个子集。下表列出了Spring AOP所支持的AspectJ切点指示器:

AspectJ指示器 描  述
arg() 限制链接点匹配参数为指定类型的执行方法
@args() 限制链接点匹配参数由指定注解标注的执行方法
execution() 用于匹配是链接点的执行方法
this() 限制链接点匹配AOP代理的bean引用为指定类型的类
target 限制链接点匹配目标对象为指定类型的类
@target() 限制链接点匹配特定的执行对象,这些对象对应的类要具备指定类型的注解
within() 限制链接点匹配指定的类型
@within() 限制链接点匹配指定注解所标注的类型(当使用Spring AOP时,方法定义在由指定的注解所标注的类里)
@annotation 限定匹配带有指定注解的链接点

在Spring中尝试使用AspectJ其余指示器时,将会抛出IllegalArgument-Exception异常

注:只有execution指示器是实际执行匹配的,而其余的指示器都是用来限制匹配的。说明execution指示器是在编写切点定义时最主要使用的指示器

编写切点

package concert;
public interface Performance
{
    public void perform();
}

Performance能够表明任何类型的现场表演,如舞台剧、电影或音乐会。设想编写Performance的perform()方法触发的通知。下图展示了一个切点表达式,这个表达式可以设置当perform()方法执行时触发通知的调用

使用AspectJ切点表达式来选择Performance的perform()方法:

图片描述

使用execution()指示器选择Performance的perform()方法。方法表达式以“*”号开始,代表了不关心方法返回值的类型。而后指定全限定类名和方法名。对于方法参数列表,使用两个点号(..)代表切点要选择任意的perform()方法,不管该方法的入参是什么

设现需配置的切点仅匹配concert包。在此场景下,可使用within()指示器限制切点范围:

图片描述

and代替“&&”,or代替“||”,not代替“!”

在切点中选择bean

Spring引入新的bean()指示器,它容许在切点表达式中使用bean的ID来标识bean。bean()使用bean ID或bean名称做为参数来限制切点只匹配特定的bean

执行Performance的perform()方法时应用通知,但限定bean的ID为woodstock:

execution(* concert.Performance.perform()) and bean('woodstock')

使用非操做为除了特定ID之外的其余bean应用通知:

execution(* concert.Performance.perform()) and !bean('woodstock')

使用注解建立切面

定义切面

//Audience类:观看演出的切面

package concert;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class Audience
{
    @Before("execution(** concert.Performance.perform(..))")        // 表演以前
    public void silenceCellPhones()
    {
        System.out.println("Silencing cell phones");
    }
    @Before("execution(** concert.Performance.perform(..))")        // 表演以前
    public void takeSeats()
    {
        System.out.println("Taking seats");
    }        
    @AfterReturning("execution(** concert.Performance.perform(..))")        // 表演以后
    public void applause()
    {
        System.out.println("CLAP CLAP CLAP!!!");
    }
    @AfterThrowing("execution(** concert.Performance.perform(..))")        // 表演失败以后
    public void demandRefound()
    {
        System.out.println("Demanding a refund");
    }
}

Audience类使用@AspectJ注解进行了标注。该注解代表Audience不只仅是一个POJO,仍是一个切面。Audience类中的方法都使用注解来定义切面的具体行为

Spring使用AspectJ注解来声明通知方法:

注  解 通  知
@After 通知方法会在目标方法返回或抛出异常后调用
@AfterReturning 通知方法会在目标方法返回后调用
@AfterThrowing 通知方法会在目标方法抛出异常后调用
@Around 通知方法会将目标方法封装起来
@Before 通知方法会在目标方法调用以前执行

为@Pointcut注解设置的值是一个切点表达式,就像以前在通知注解上所设置的那样。经过在performance()方法上添加@Pointcut注解,实际上扩展了切点表达式语言,这样就能够在任何的切点表达式中使用performance()了,若是不这样作的话,须要在这些地方使用那个更长的切点表达式

如今把全部通知注解中的长表达式都替换成了performance(),该方法的实际内容并不重要,在这里其实是空的。其实该方法自己只是一个标识,供@Pointcut注解依附

// 经过@Pointcut注解声明频繁使用的切点表达式

package concert;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class Audience
{
    @Pointcut("execution(** concert.Performance.perform(..))")        //定义命名的切点
    public void performance(){}
    
    @Before("performance()") 
    public void silenceCellPhones()
    {
        System.out.println("Silencing cell phones");
    }
    @Before("execution(** concert.Performance.perform(..))")        // 表演以前
    public void takeSeats()
    {
        System.out.println("Taking seats");
    }        
    @AfterReturning("performance()")        // 表演以后
    public void applause()
    {
        System.out.println("CLAP CLAP CLAP!!!");
    }
    @AfterThrowing("performance()")        // 表演失败以后
    public void demandRefound()
    {
        System.out.println("Demanding a refund");
    }
}

像其余的Java类同样,它能够装配为Spring中的bean:

@Bean 
public Audience audience()
{
    return new Audience();
}

经过上述操做,Audience只会是Spring容器中的一个bean。即使使用了AspectJ注解,但它并不会被视为切面,这些注解不会解析,也不会建立将其转换为切面的代理

使用JavaConfig能够在配置类的类级别上经过使用EnableAspectJ-AutoProxy注解启用自动代理功能:

package concert;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

// 启动AspectJ自动代理
@Configuration                
@EnableAspectJAutoProxy
@ComponentScan

public class ConcertConfig
{
    @Bean
    public Audience audience()
    {
        return new Audience();
    }
}

使用XML来装配bean须要使用Springaop命名空间中的<aop:aspectj-autoproxy>元素

// 在XML中,经过Spring的aop命名空间启用AspectJ自动代理
<?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"        // 声明Spring的aop命名空间
    xsi:schemaLocation="http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <context:component-scan base-package = "concert" />
    <aop:aspectj-autoproxy />                // 启动AspectJ自动代理
    <bean class= "concert.Audience" />        // 声明Audience bean
</beans>

JavaConfig和XML配置,AspectJ自动代理都会为使用@Aspect注解的bean建立一个代理,这个代理会围绕着全部该切面的切点所匹配的bean。在这种状况下,将会为Concert bean建立一个代理,Audience类中的通知方法将会在perform()调用先后执行

Spring的AspectJ自动代理仅仅使用@AspectJ做为建立切面的指导,切面依然是基于代理的。在本质上,它依然是
Spring基于代理的切面。这一点很是重要,由于这意味着尽管使用的是@AspectJ注解,但咱们仍然限于代理方法的调用。若是想利用AspectJ的全部能力,咱们必须在运行时使用AspectJ而且不依赖Spring来建立基于代理的切面

建立环绕通知

环绕通知是最为强大的通知类型。可以让所编写的逻辑被通知的目标方法彻底包装起来。实际上就像在一个通知方法中同时编写前置通知和后置通知

// 使用环绕通知从新实现Audience切面
package concert;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class Audience
{
    @Pointcut("execution(** concert.Performance.perform(..))")        //定义命名的切点
    public void performance(){}
    
    @Around("performance()") 
    public void watchPerformance(ProceedingJoinPoint jp)
    {
        try{
            System.out.println("Silencing cell phones");
            System.out.println("Taking seats");
            jp.proceed();
            System.out.println("CLAP CLAP CLAP!!!");
        } catch(Throwable e){
            System.out.println("Demanding a refund");
        }
    }
}

@Around注解代表watchPerformance()方法会做为performance()切点的环绕通知。首先接受ProceedingJoinPoint做为参数。这个对象是必需要有的,由于在通知中须要经过它来调用被通知的方法。通知方法中能够作任何的事情,当要将控制权交给被通知的方法时,它须要调用ProceedingJoinPoint的proceed()方法

注:调用proceed()方法。如不调该方法,那么通知实际上会阻塞对被通知方法的调用;若不调用proceed()方法,会阻塞对被通知方法的访问,与之相似,也能够在通知中对它进行屡次调用

处理通知中的参数

建立TrackCounter类,用来记录每一个磁道所播放的次数,是通知playTrack()方法的一个切面。下面的程序清单展现了这个切面:

// 使用参数化的通知来记录磁道播放的次数
package soundsystem;
import java.util.HashMap;
import java.util.Map;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class TrackCounter
{
    private Map<Integer, Integer> TrackCounts = new HashMap<Integer, Integer>();
    
    // 通知playTrack()方法
    @Pointcut(
        "execution(* soundsystem.CompactDisc.playTrack(int))" +
        "&& args(trackNumber)" )
    public void trackPlayed(int trackNumber){}
    
    @Before("trackPlayed(trackNumber)")            // 在播放前,为该磁道计数
    public void countTrack(int trackNumber)
    {
        int currentCount = getPlayCount(trackNumber);
        trackCounts.put(trackNumber, currentCount + 1);
    }
    
    public int getPlayCount(int trackNumber)
    {
        return trackCounts.containsKey(trackNumber) ? trackCounts.get(trackNumber) : 0;
    }
}

在切点表达式中声明参数,这个参数传入到通知方法中:
图片描述

切点表达式中的args(trackNumber)限定符。代表传递给playTrack()方法的int类型参数也会传递到通知中去。参数的名称trackNumber也与切点方法签名中的参数相匹配

这个参数会传递到通知方法中,这个通知方法是经过@Before注解和命名切点trackPlayed(trackNumber)定义的。切点定义中的参数与切点方法中的参数名称是同样的,这样就完成了从命名切点到通知方法的参数转移

// 配置TrackCount记录每一个磁道播放的次数
package soundsystem;
import java.util.ArrayList;
import java.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@EnableAspectJAutoProxy                    // 启用AspectJ自动代理
public class TrackCounterConfig
{
    @Bean
    public CompactDisc sgtPeppers()        // CompactDisc bean
    {
        BlankDisc cd = new BlankDisc();
        cd.setTitle("Sgt. Pepper's Lonely Hearts Club Band");
        cd.setArtist("The Beales");
        List<String> tracks = new ArrayList<String>();
        tracks.add("Sgt. Pepper's Lonely Hearts Club Band");
        tracks.add("With a Little Help from My Friends");
        tracks.add("Lucy in the Sky with Diamonds");
        tracks.add("Getting Better");
        tracks.add("Fixing a Hole");
        
        // ...other tracks omitted for brevity...
        cd.setTracks(tracks);
        return cd;
    }
    
    @Bean
    public TrackCounter trackCounter()        // TrackCounter bean
    {
        return new TrackCounter();
    }
}

经过注解引入新功能

使用Spring AOP,咱们能够为bean引入新的方法。代理拦截调用并委托给实现该方法的其余对象
图片描述

为示例中的全部的Performance实现引入下面的Encoreable接口:

package concert;
public interface Encoreable
{
    void performEncore();
}

借助于AOP的引入功能,没必要在设计上妥协或者侵入性地改变现有的实现。为了实现该功能,建立一个新
的切面:

package concert;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.DeclareParents;

@Aspect
public class EncoreableIntroducer
{
    @DeclareParents(value = "concert.Performance+", defaultImpl = DefaultEncoreable.class)
    public static Encoreable encoreable;
}

EncoreableIntroducer是一个切面。可是它与以前所建立的切面不一样,并无提供前置、后置或环绕通知,而是
经过@DeclareParents注解,将Encoreable接口引入到Performance bean中

@DeclareParents注解由三部分组成:

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

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

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

和其余的切面同样,须要在Spring应用中将EncoreableIntroducer声明为一个bean:

<bean class = "concert.EncoreableIntroducer" />

Spring的自动代理机制将会获取到它的声明,当Spring发现一个bean使用了@Aspect注解时,Spring就会建立一个代理,而后将调用委托给被代理的bean或被引入的实现,这取决于调用的方法属于被代理的bean仍是属于被引入的接口

注入AspectJ切面

为演出建立一个新切面。具体来说,以切面的方式建立一个评论员的角色,他会观看演出而且会在演出以后提供一些批评意见

// 使用AspectJ实现表演的评论员
package concert;
public aspect CriticAspect{
    public CriticAspect(){}
    
    pointcut performance() : execution(* perform(..));
    afterReturning() : performance()
    {
        System.out.println(criticismEngine.getCriticism());
    }
    private CriticismEngine criticismEngine;
    
    public void setCriticismEngine(CriticismEngine criticismEngine)        // 注入CriticismEngine
    {
        this.criticismEngine = criticismEngine;
    }
}

上述程序中的performance()切点匹配perform()方法。当它与afterReturning()通知一块儿配合使用时,可让该切面在表演结束时起做用

实际上,CriticAspect与一个CriticismEngine对象相协做,在表演结束时,调用该对象的getCriticism()方法来发表一个苛刻的评论。为了不CriticAspect和CriticismEngine之间产生没必要要的耦合,咱们经过Setter依赖注入为CriticAspect设置CriticismEngine。此关系以下图所示:

图片描述

切面也须要注入。像其余的bean同样,Spring能够为AspectJ切面注入依赖

\\ 要注入到CriticAspect中的CriticismEngine实现
package com.springinaction.springidol;
public class CriticismEngineImpl implements CriticismEngine
{
    public CriticismEngineImpl(){}
    
    public String getCriticism()
    {
        int i = (int) (Math.random() * criticismPool.length)
        return criticismPool[i];
    }
    
    // injected
    private String[] criticismPool;
    public void setCriticismPool(String[] criticismPool)
    {
        this.criticismPool = criticismPool;
    }
}

CriticismEngineImpl实现了CriticismEngine接口,经过从注入的评论池中随机选择一个苛刻的评论

使用XML声明Spring bean:

<bean id = "criticismEngine"
    class = "com.springinaction.springidol.CriticismEngineImpl">
    <property name = "criticisms">
        <list>
            <value>Worst performance ever!</value>
            <value>I laughed, I cried, then I realized I was at the wrong show.</value>
            <value>A must see show!</value> 
        </list>
    </property>
</bean>

如今有了一个要赋予CriticAspect的Criticism-Engine实现。剩下的就是为CriticAspect装配CriticismEngineImple。在展现如何实现注入以前,必须清楚AspectJ切面根本不须要Spring就能够织入到咱们的应用中。若是想使用Spring的依赖注入为AspectJ切面注入协做者,那咱们就须要在Spring配置中把切面声明为一个Spring配置中的<bean>。以下的<bean>声明会把criticismEnginebean注入到CriticAspect中:

<bean class= "com.springinaction.springidol.CriticAspect"
    factory-method = "aspectOf">
    <property name = "criticismEngine" ref = "criticismEngine" />
</bean>

Spring须要经过aspectOf()工厂方法得到切面的引用,而后像<bean>元素规定的那样在该对象上执行依赖注入

相关文章
相关标签/搜索