本章内容:
面向切面编程的基本原理
通过POJO创建切面
使用@AspectJ注解
为AspectJ切面注入依赖
在软件开发中,散布于应用中多的功能被称为横切关注点(cross-cutting concern)。通常来讲,这些横切关注点从概念上是与应用的业务逻辑相分离的(但往往会直接嵌入到应用的业务逻辑之中)。把这些横切关注点与业务相分离正是面向切面编程(AOP)所要解决的问题。
切面的应用场景包括:日志、安全和事务管理等。
4.1 什么是面向切面编程
在使用面向切面编程时,我们仍然在一个地方定义通用功能,但是可以通过声明的方式定义这个功能要以何种方式在何处应用,而无需修改受影响的类。横切关注点可以被模块化为特殊的类,这些类被称为切面(aspect)。
描述切面的常用术语有通知(advice)、切点(pointcut)和连接点(join point)。
通知(Advice)
在AOP术语中,切面的工作被称为通知。
Spring切面可以应用5种类型的通知:
前置通知(Before):在目标方法被调用之前调用通知功能;
后置通知(After):在目标方法完成之后调用通知,此时不会关心方法的输出是什么;
返回通知(After-returning ):在目标方法成功执行之后调用通知;
异常通知(After-throwing):在目标方法抛出异常后调用通知;
环绕通知(Around):通知包裹了被通知的方法,在被通知的方法调用之前和调用之后执行自定义的行为。
连接点(Join point)
应用可能有数以千计的时机应用通知。这些时机被称为连接点。连接点是在应用执行过程中能够插入切面的一个点。这个点可以是调用方法时、抛出异常时、甚至修改一个字段时。切面代码可以利用这些点插入到应用的正常流程之中,并添加新的行为。
切点(Pointcut)
切点的定义会匹配通知所要织入的一个或多个连接点。我们通常使用明确的类和方法名称,或是利用正则表达式定义所匹配的类和方法名称来指定这些切点。
切面(Aspect)
切面是通知和切点的结合。通知和切点共同定义了切面的全部内容。
引入(Introduction)
引入允许我们向现有类添加新方法或属性。
织入(Weaving)
织入是把切面应用到目标对象并创建新的代理对象的过程。切面在指定的连接点被织入到目标对象中。在目标对象的生命周期里有多少个点可以进行织入:
编译期:切面在目标类编译时被织入。AspectJ的织入编译器是以这种方式织入切面的。
类加载期:切面在目标类加载到JVM时被织入。需要特殊的类加载器,它可以在目标类被引入应用之前增强该目标类的字节码。AspectJ5的加载时织入就支持以这种方式织入切面。
运行期:切面在应用运行的某个时刻被织入。一般情况下,在织入切面时,AOP容器会为目标对象动态地创建一个代理对象。SpringAOP就是以这种方式织入切面。
Spring提供了4种类型的AOP支持:
基于代理的经典SpringAOP;
纯POJO切面;
@AspectJ注解驱动的切面;
注入式AspectJ切面。
Spring在运行时通知对象
通过在代理类中包裹切面,Spring在运行期把切面织入到Spring管理的bean中。代理封装了目标类,并拦截被通知方法的调用,再把调用转发给真正的目标bean。当代理拦截到方法调用时,在调用目标bean方法之前,会执行切面逻辑。
直到应用需要被代理的bean时,Spring才创建代理对象。如果使用的是ApplicationContext的话,在ApplicationContext从BeanFactory中加载所有bean的时候,Spring才会创建被代理的对象。因为Spring运行时才创建代理对象,所以我们不需要特殊的编译器来织入SpringAOP的切面。
Spring只支持方法级别的连接点
因为Spring基于动态代理,所以Spring只支持方法连接点。Spring缺少对字段连接点的支持,而且它不支持构造器连接点。方法之外的连接点拦截功能,我们可以利用Aspect来补充。
4.2 通过切点来选择连接点
在Spring AOP中,要使用AspectJ的切点表达式语言来定义切点。
由于Sring是基于代理的,而某些切点表达式是与基于代理的AOP无关的。下表列出了Spring AOP所支持的AspectJ切点指示器。
在Spring中尝试使用AspectJ其他指示器时,将会抛出IllegalArgument-Exception异常。
注意:当我们查看如上所展示的这些Spring支持的指示器时,只有execution指示器是实际执行匹配的,而其他的指示器都是用来限制匹配的。
编写切点
为了阐述Spring中的切面,我们定义一个Performance接口:
package concert;public interface Performance {public void perform() ;}
假设我们想编写Performance的perform()方法触发的通知,下面展示了切点表达式的写法
使用AspectJ切点表达式来选择Performance的perform()方法
现在假设我们需要配置的切点仅匹配concert包。我们可以使用within()指示器来限制匹配,如下图
使用within指示器限制切点范围
注意:我们使用了“&&”操作符把execution()和within()指示器连接在一起形成与(可以用and代替)关系(切点必须匹配所有的指示器)。类似地,我们可以使用“||操作符”来标识或(可以用or代替)关系,而使用“!”操作符来标识非(可以用not代替)操作。
在切点中选择bean
除了表所列的指示器外,Spring还引入了一个新的bean()指示器,它允许我们在切点表达式中使用bean的ID来标识bean。bean()使用beanID或bean名称作为参数限制切点只匹配特定的bean。
例如,考虑如下的切点:
execution(* concert.Performance.perform()) and bean('woodstock')
还可以使用非操作为除了特定ID以外的其他bean应用通知:
execution(* concert.Performance.perform()) and !bean('woodstock')
4.3 使用注解创建切面
我们已经定义了Performance接口,它是切面中切点的目标对象。现在,让我们使用AspectJ注解来定义切面
AspectJ提供了五个注解来定义通知,如下表所示。
定义切面
我们将观众定义为一个切面,并将其应用到演出上就是较为明智的做法。
下面为Audience类的代码
package com.springinaction.perf;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.*;//切面 POJO@Aspectpublic class Audience {//定义命名的切点@Pointcut("execution(** com.springinaction.perf.Performance.perform(..))")public void performance(){ }//定义通知@Before("performance()") // 表演之前public void silenceCellPhones(){ System.out.println("Silencing cell phones"); }@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("performance()") // 环绕通知方法public void watchPerformance(ProceedingJoinPoint jp){try { System.out.println("Silencing cell phones Again"); System.out.println("Taking seats Again"); jp.proceed(); System.out.println("CLAP CLAP CLAP Again"); }catch (Throwable e){ System.out.println("Demanding a refund Again"); } }}
关于环绕通知,我们首先注意到它接受ProceedingJoinPoint作为参数。这个对象是必须要有的,因为要在通知中通过它来调用被通知的方法。
需要注意的是,一般情况下,别忘记调用proceed()方法。如果不调用,那么通知实际上会阻塞对被通知方法的调用,也许这是所期望的效果。当然,也可以多次调用,比如要实现一个场景是实现重试逻辑。
除了注解和没有实际操作的performance()方法,Audience类依然是一个POJO,可以装配为Spring中的bean
@Beanpublic Audience audience(){ // 声明Audiencereturn new Audience();}
除了定义切面外,还需要启动自动代理,才能使这些注解解析。如果使用JavaConfig的话,需要如下配置
package com.springinaction.perf;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@ComponentScan@EnableAspectJAutoProxy //启动AspectJ自动代理public class AppConfig {@Beanpublic Audience audience(){ // 声明Audiencereturn new Audience(); }}
假如在Spring中要使用XML来装配bean的话,那么需要使用Spring aop命名空间中的元素。
<?xml version="1.0" encoding="UTF-8"?>xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd 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">
无论使用JavaConfig还是XML,Aspect自动代理都会使用@Aspect注解的bean创建一个代理,这个代理会围绕着所有该切面的切点所匹配的bean。这种情况下,将会为Concert的bean创建一个代理,Audience类中的通知方法将会在perform()调用前后执行。
我们需要记住的是,Spring的AspectJ自动代理仅仅使用@AspectJ作为创建切面的指导,切面依然是基于代理的。本质上,它依然是Spring基于代理的切面。
处理通知中的参数
目前为止,除了环绕通知,其他通知都没有参数。如果切面所通知的方法确实有参数该怎么办呢?切面能访问和使用传递给被通知方法的参数吗?
为了阐述这个问题,我们来重新看一下BlankDisc样例。假设你想记录每个磁道被播放的次数。为了记录次数,我们创建了TrackCounter类,它是通知playTrack()方法的一个切面。
package com.springinaction.disc;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import java.util.HashMap;import java.util.Map;@Aspectpublic class TrackCounter {private Map trackCounts = new HashMap<>();@Pointcut("execution(* com.springinaction.disc.CompactDisc.playTrack(int))" +"&& args(trackNumber)") // 通知playTrack()方法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也与切点方法签名中的参数相匹配。切点定义中的参数与切点方法中的参数名称是一样的。
下面我们启动AspectJ自动代理以及定义bean
package com.springinaction.disc;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.EnableAspectJAutoProxy;import java.util.ArrayList;import java.util.List;@Configuration@EnableAspectJAutoProxypublic class TrackCounterConfig {@Beanpublic CompactDisc sgtPeppers(){ BlankDisc cd = new BlankDisc(); cd.setTitle("Sgt. Pepper's Lonely Hearts Club Band"); cd.setArtist("The Beatles"); List tracks = new ArrayList<>(); tracks.add("Sgt. Pepper's Lonely Hearts Club Band"); tracks.add("With a Little Help from My Friends"); tracks.add("Luck in the Sky with Diamonds"); tracks.add("Getting Better"); tracks.add("Fixing a Hole"); tracks.add("Feel My Heart"); tracks.add("L O V E"); cd.setTracks(tracks);return cd; }@Beanpublic TrackCounter trackCounter(){return new TrackCounter(); }}
最后的简单测试
package com.springinaction;import static org.junit.Assert.*;import com.springinaction.disc.CompactDisc;import com.springinaction.disc.TrackCounter;import com.springinaction.disc.TrackCounterConfig;import org.junit.Rule;import org.junit.Test;import org.junit.runner.RunWith;import org.junit.contrib.java.lang.system.StandardOutputStreamLog;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = TrackCounterConfig.class)public class TrackCounterTest { @Rule public final StandardOutputStreamLog log = new StandardOutputStreamLog(); @Autowired private CompactDisc cd; @Autowired private TrackCounter counter; @Test public void testTrackCounter(){cd.playTrack(1);cd.playTrack(2);cd.playTrack(3);cd.playTrack(3);cd.playTrack(3);cd.playTrack(3);cd.playTrack(7);cd.playTrack(7);assertEquals(1,counter.getPlayCount(1));assertEquals(1,counter.getPlayCount(2));assertEquals(4,counter.getPlayCount(3));assertEquals(0,counter.getPlayCount(4));assertEquals(0,counter.getPlayCount(5));assertEquals(0,counter.getPlayCount(6));assertEquals(2,counter.getPlayCount(7)); }}
通过注解引入新功能
我们除了给已有的方法添加新功能外,还可以添加一些额外的功能。
回顾一下,在Spring中,切面只是实现了它们所包装bean相同的接口代理。如果除了实现这些接口,代理也能暴露新接口。即便底层实现类并没有实现这些接口,切面所通知的bean也能实现新的接口。下图展示了它们是如何工作的。
使用Spring AOP,我们可以为bean引入新的方法。代理拦截调用并委托给实现该方法的其他对象
需要注意的是,当引入接口的方法被调用时,代理会把此调用委托给实现了新接口的某个其他对象。实际上,一个bean的实现被拆分到了多个类中。
为了验证能行得通,我们为所有的Performance实现引入Encoreable接口
package com.springinaction.perf;public interface Encoreable {void performEncore();}
借助于AOP,我们创建一个新的切面
package com.springinaction.perf;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.DeclareParents;@Aspectpublic class EncoreableIntroducer { // 需要给Performance和其实现类额外添加方法的实现@DeclareParents(value = "com.springinaction.perf.Performance+", defaultImpl = DefaultEncoreable.class)public static Encoreable encoreable;}
其中@DeclareParents注解,将Encoreable接口引入到Performance bean中。
@DeclareParents注解有三个部门组成:
value属性指定了哪种类型的bean要引入该接口。(本例中,就是Performance,加号表示Performance的所有子类型)
defaultImpl属性指定了为引入功能提供实现的类。
@DeclareParents注解所标注的静态属性指明了要引入的接口。
然后需要在配置中声明EncoreableIntroducer的bean
@Beanpublic EncoreableIntroducer encoreableIntroducer(){return new EncoreableIntroducer();}
当调用委托给被代理的bean或被引入的实现,取决于调用的方法属性被代理的bean还是属性被引入的接口。
在Spring中,注解和自动代理提供了一种很便利的方式来创建切面。但有一个劣势:必须能够为通知类添加注解,要有源码。
如果没有源码或者不想注解到你的代码中,能可选择Spring XML配置文件中声明切面。
4.4 在XML中声明切面
如果声明切面,但不能为通知类添加注解时,需要转向XML配置了。
在Spring的aop命名空间中,提供了多个元素用来在XML中声明切面,如下表所示
我们重新看一下Audience类,这一次我们将它所有的AspectJ注解全部移除掉:
package com.springinaction.perf;public class Audience {public void silenceCellPhones(){ System.out.println("Silencing cell phones"); }public void takeSeats(){ System.out.println("Taking seats"); }public void applause(){ System.out.println("CLAP CLAP CLAP"); }public void demandRefund(){ System.out.println("Demanding a refund"); }public void watchPerformance(ProceedingJoinPoint jp){try { System.out.println("Silencing cell phones Again"); System.out.println("Taking seats Again"); jp.proceed(); System.out.println("CLAP CLAP CLAP Again"); }catch (Throwable e){ System.out.println("Demanding a refund Again"); } }}
声明前置、后置以及环绕通知
下面展示了所需要的XML
<?xml version="1.0" encoding="UTF-8"?>xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
为通知传递参数
我们使用XML来配置BlankDisc。
首先,移除掉TrackCounter上所有的@AspectJ注解。
package com.springinaction.disc;import java.util.HashMap;import java.util.Map;public class TrackCounter {private Map trackCounts = new HashMap<>();// 在播放前,为该磁道计数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; }}
下面展示了在XML中将TrackCounter配置为参数化的切面
<?xml version="1.0" encoding="UTF-8"?>xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">Sgt. Pepper's Lonely Hearts Club BandWith a Little Help from My FriendsLucy in the Sky with DiamondsGetting BetterFixing a HoleFeel My HeartL O V E execution(* com.springinaction.disc.CompactDisc.playTrack(int)) and args(trackNumber)" />
注意:在XML中,“&”符号会被解析为实体的开始,所用“and”关键字。
通过切面引入新的功能
使用Spring aop命名空间中的元素,我们可以实现相同的功能。
implement-interface="com.springinaction.perf.Encoreable"default-impl="com.springinaction.perf.DefaultEncoreable" />
我们还可以使用delegate-ref属性来标识
implement-interface="com.springinaction.perf.Encoreable"delegate-ref="defaultEncoreable" />
delegate-ref属性引用了一个Spring bean作为引入的委托。
4.5 注入AspectJ切面
AspectJ提供了Spring AOP所不能支持的许多类型的切点。例如:构造器切点就非常方便。
为了演示,我们新创建一个切面,我们以切面的方式创建一个评论员的角色,演出后提一些批评意见。
首先创建这样的一个切面
package com.springinaction.perf;public aspect CriticAspect {public CriticAspect(){}pointcut performance() : execution(* perform(..)); after() returning : performance() { System.out.println(criticismEngine.getCriticism()); }private CriticismEngine criticismEngine;public CriticismEngine getCriticismEngine() {return criticismEngine; }public void setCriticismEngine(CriticismEngine criticismEngine) {this.criticismEngine = criticismEngine; }}
然后是CriticismEngine的接口
package com.springinaction.perf;public interface CriticismEngine {String getCriticism();}
CriticismEngine的实现类
package com.springinaction.perf;public class CriticismEngineImpl implements CriticismEngine {public CriticismEngineImpl(){}@Overridepublic String getCriticism() {int i = (int) (Math.random() * criticismPool.length);return criticismPool[i]; }private String[] criticismPool;public void setCriticismPool(String[] criticismPool){this.criticismPool = criticismPool; }}
为CriticismEngineImpl注入list
Worst performance ever!I laughed, I cried, then I realized I was at the wrong show.A must see show!
在展示如何实现注入之前,我们必须清楚AspectJ切面根本不需要Spring就可以织入到我们的应用中。如果想使用Spring的依赖注入,那就需要把切面声明为一个Spring配置中的。
通常情况下,Spring bean由Spring容器初始化,但是AspectJ切面AspectJ在运行期创建的。等到Spring有机会为CriticAspect注入CriticismEngine时,CriticAspect已经被实例化了。
因为Spring不能负责创建CriticAspect,那就不能在Spring中简单地把CriticAspect声明为一个bean。相反,我们需要一种方式为Spring获得已经有AspectJ创建的CriticAspect实例的句柄,从而可以注入CriticismEngine。幸好,所有AspectJ切面都提供了一个静态的aspectOf()方法,该方法返回切面的一个单例。所有为了获得切面的实例,我们必须使用factory-method来调用aspectOf()而不是调用CriticAspect的构造器方法。
简而言之,Spring不能像之前那样使用声明来创建一个CriticAspect实例-它已经在运行时有AspectJ创建完成了。Spring需要通过aspectOf()工厂方法获得切面的引用,然后像
元素规定的那样在该对象上执行依赖注入。
4.6 小结
AOP是面向对象编程的一个强大补充。通过AspectJ,我们现在可以把之前分散在应用各处的行为放入可重用的模块中。我们显示地声明在何处如何应用该行为。这有效减少了代码冗余,并让我们的类关注自身的主要功能。
Spring提供了一个AOP框架,让我们把切面插入到方法执行的周围。
现在我们已经学会如何把通知织入前置、后置和环绕方法的调用中,以及为处理异常增加自定义的行为。关于在Spring应用中如何使用切面,我们可以有多种选择。通过使用@AspectJ注解和简化的配置命名空间,在Spring中装配通知和切点变得非常简单。
最后,当Spring AOP不能满足需求时,我们必须转向更为强大的AspectJ。对于这些场景,我们了解了如何使用Spring为AspectJ切面注入依赖。
此时此刻,我们已经覆盖了Spring框架的基础知识,了解到如何配置Spring容器以及如何为Spring管理的对象应用切面。正如我们所看到的,这些核心技术为创建松散耦合的应用奠定了坚实的基础。现在,我们越过这些基础的内容,看一下如何使用Spring构建真实的应用。从下一章开始,首先看到的是如何使用Spring构建Web应用。
原文地址:
https://thinkwon.blog.csdn.net/article/details/103541166