在直系学长曾经的指导下,参考了直系学长的博客(https://www.cnblogs.com/WellHold/p/6655769.html)学习Spring的另一个核心概念--面向切片编程,即AOP(Aspect Oriented Programming)。

  Java是一种经典的面向对象的编程语言(OOP,Object Oriented Programming)。而面向对象的编程语言有三大特性:封装、继承和多台。其中继承允许我们定义从上到下的关系,即子类可以继承父类的一些功能参数,也可以改写父类的一些功能参数。但是,要为分散的对象(即不是同一父类的对象,这里的父类不包括Object)引入一个公共的行为的时候,OOP就显得很乏力,它需要在每一个对象里头都添加这个共用的行为,这样的代码就会显得很重复,很繁杂,最典型的就是添加日志功能,这个日志功能和对象的核心功能毫无关系,但是腰围分散的对象添加日志功能,就必须打开每一个分散的封装好的对象,然后添加日志功能代码,将这种分散在各处与对象核心功能无关的代码,称为横切代码。为了解决这个问题,AOP就应用而生。

  AOP是将多个类的公共行为封装到一个可重用的模块(如我们上一段所说的日志功能)并将其命名为“Aspect”,即是说将那些和类的核心业务无关的,却为业务模块所公共调用的逻辑处理封装起来,便可以减少系统的重复代码,降低模块间的耦合度,并有利于未来的可操作性和可维护性。AOP弥补了OOP在横向关系上操作的不足。而实现AOP的技术的主要两种方式,其中一种就是我们《常用设计模式:代理模式》所提到的动态代理技术;还有一种方式就是采用静态织入的方式,引入特定的语法创建“方面”,从而使得编译器可以在编译期间织入有关“方面”的代码。

  Spring的AOP的实现原理就是动态代理技术。

  一、代理模式

  通过之前学习过的设计模式可以知道,简而言之,代理模式就是:“代理人”尽力肩负着工作使命,当“代理人”不能解决某些问题时,就会“转交”给“本人”,这里的“转交”就是“委托”。

  那么,究竟什么是代理模式呢?所谓的代理模式,主要分为一下几个角色:1.代理方;2.目标方;3.客户方;为了让读者和将来的自己能够更好的理解这三个角色,举个例子,比如我们要在买一双鞋子,但是鞋店离我们很远,我们需要让一个朋友帮我们代购,那么在这个关系当中,我们就是作为客户方,朋友作为代理方,而鞋店则是目标方,我们需要做的是要讲我们要买的鞋子的需求告诉朋友听,然后朋友帮我们到店里去购买,购买之后还可以为我们的鞋子简单的包装之后再邮寄回我们。这就是代理的三方关系,从这个例子我们可以给出代理的定义:为其他对象提供一种代理以控制对这个对象的访问。在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用, 其特征是代理类与委托类有同样的接口。

  在进一步理解这个代理类的作用,代理类除了能帮我们把消息递交给目标类之外,还可以为目标类预处理消息,过滤消息,事后处理消息等。在我们的例子中的体现就是朋友不仅可以帮我们买鞋子,还可以为鞋店提供一些购买请求的过滤,比如我们要买的鞋子如果鞋店没有,朋友会直接告诉我们没有这双鞋,而不需要到鞋店去再问一遍,并且在我们购买到鞋子之后,朋友还会负责之后的邮寄和鞋子的包装,这就是相当于代理类为目标类做的消息预处理,消息过滤,以及事后消息预处理。代理类的对象本身并不真正实现服务,而是通过调用目标类的对象的相关方法,来提供特定的服务,从我们的例子来看,朋友自身是不生产鞋子的,而是鞋店生产的鞋子,并且提供销售,是一个道理。真正的业务是由目标类来实现的,但是在实现目标类之前的一些公共服务,例如在项目开发中我们没有加入缓冲,日志这些功能,后期想加入,我们就可以使用代理来实现,而没有必要打开已经封装好的目标类。

  (1)静态代理模式(单个接口)

  静态代理模式,就是由程序员创建或特定工具自动生成的源代码,再对其编译。在程序运行前,代理的类文件就已经存在。

  以买鞋子为例,结合示例程序理解静态代理模式:

  • 首先为了保持代理类和目标类的一致性,定义一个通用接口:
 package bjtu.bigjunoba.staticProxy;

 public interface BuyShoes {

     public void BuyTheShoes();
}
  • 然后编写目标类方法:
 package bjtu.bigjunoba.staticProxy;

 public class ShoesSeller implements BuyShoes {

     @Override
public void BuyTheShoes() {
System.out.println("我是鞋店老板,即目标类,你执行了BuyTheShoes()这个方法就可以买到鞋了!");
} }
  • 然后编写代理类方法,代理类中会调用目标类的方法,这里要注意的是,目标类的BuyTheShoes()方法被增强了,即实现了预处理和事后处理的逻辑代码块
 package bjtu.bigjunoba.staticProxy;

 public class ShoesSellerProxy implements BuyShoes {

     private ShoesSeller shoesSeller;

     public ShoesSellerProxy(ShoesSeller shoesSeller) {
this.shoesSeller = shoesSeller;
}
@Override
public void BuyTheShoes() {
System.out.println("我是帮你买鞋的朋友,即代理类,(预先处理)我要去执行鞋店老板的BuyTheShoes()方法,就可以帮你买鞋!");
shoesSeller.BuyTheShoes();
System.out.println("我是帮你买鞋的朋友,即代理类,(事后处理)我已经执行鞋店老板的BuyTheShoes()方法,买到了你的鞋子!");
} }
  • 最后,客户类调用代理类中的方法:
 package bjtu.bigjunoba.staticProxy;

 public class BuyShoesClient {
public static void main(String[] args) {
ShoesSeller seller = new ShoesSeller();
ShoesSellerProxy sellerProxy = new ShoesSellerProxy(seller);
System.out.println("我是客户方,我要执行代理方的BuyTheShoes()方法,就可以让朋友帮我买到鞋!");
sellerProxy.BuyTheShoes();
}
  • 输出:
我是客户方,我要执行代理方的BuyTheShoes()方法,就可以让朋友帮我买到鞋!
我是帮你买鞋的朋友,即代理类,(预先处理)我要去执行鞋店老板的BuyTheShoes()方法,就可以帮你买鞋!
我是鞋店老板,即目标类,你执行了BuyTheShoes()这个方法就可以买到鞋了!
我是帮你买鞋的朋友,即代理类,(事后处理)我已经执行鞋店老板的BuyTheShoes()方法,买到了你的鞋子!

  (2)静态代理模式(两个接口)

  上例中的一个代理类只实现一个业务接口可以很好地理解代理模式这个概念。当然,一个代理类也可以实现多个接口,也就是说朋友既可以帮我买鞋子,也可以帮我买手机。

  对于事前处理和事后处理来说,不管是买鞋子还是买手机都是相同的流程:选好商品准备给钱--老板按照商品收钱--拿好商品发我快递。观察SellerProxy类可以发现:这个代理类需要重写很多业务方法,看起来特别冗杂。所以可以通过动态代理模式来解决这个问题。

  代码结构为:

  

  • 定义买鞋子接口:
 package bjtu.bigjunoba.staticProxy;

 public interface BuyShoes {

     public void BuyTheShoes();
}
  • 定义买手机接口:
 package bjtu.bigjunoba.staticProxy;

 public interface BuyPhone {

     public void BuyThePhone();
}
  • 实现了买鞋子接口的目标类:
 package bjtu.bigjunoba.staticProxy;

 public class ShoesSeller implements BuyShoes {

     @Override
public void BuyTheShoes() {
System.out.println("我是鞋店老板,即目标类,你把钱给我就可以拿走你要的鞋了!");
} }
  • 实现了买手机接口的目标类:
 package bjtu.bigjunoba.staticProxy;

 public class PhoneSeller implements BuyShoes {

     @Override
public void BuyTheShoes() {
System.out.println("我是手机店老板,即目标类,你把钱给我就可以拿走你要的手机了!");
} }
  • 代理类,同时实现了买鞋子和买手机,并且包括相同的事前事后处理:
 package bjtu.bigjunoba.staticProxy;

 public class SellerProxy implements BuyShoes, BuyPhone {

     private ShoesSeller shoesSeller;
private PhoneSeller phoneSeller; public SellerProxy(ShoesSeller shoesSeller) {
this.shoesSeller = shoesSeller;
} public SellerProxy(PhoneSeller phoneSeller) {
this.phoneSeller = phoneSeller;
} @Override
public void BuyTheShoes() {
System.out.println("我是你的朋友,即代理类,(事前处理)朋友选好了商品,准备把钱付给店家。");
shoesSeller.BuyTheShoes();
System.out.println("我是你的朋友,即代理类,(事后处理)朋友拿到了商品,并把商品发了快递。");
}
@Override
public void BuyThePhone() {
System.out.println("我是你的朋友,即代理类,(事前处理)朋友选好了商品,准备把钱付给店家。");
phoneSeller.BuyTheShoes();
System.out.println("我是你的朋友,即代理类,(事后处理)朋友拿到了商品,并把商品发了快递。");
} }
  • 客户类,调用代理类的方法:
 package bjtu.bigjunoba.staticProxy;

 public class BuyerClient {
public static void main(String[] args) { ShoesSeller sSeller = new ShoesSeller();
PhoneSeller pSeller = new PhoneSeller(); SellerProxy sSellerProxy = new SellerProxy(sSeller);
SellerProxy pSellerProxy = new SellerProxy(pSeller); System.out.println("我是客户方,我要买鞋!");
sSellerProxy.BuyTheShoes(); System.out.println("我是客户方,我要买手机!");
pSellerProxy.BuyThePhone();
}
}
  • 输出:
我是客户方,我要买鞋!
我是你的朋友,即代理类,(事前处理)朋友选好了商品,准备把钱付给店家。
我是鞋店老板,即目标类,你把钱给我就可以拿走你要的鞋了!
我是你的朋友,即代理类,(事后处理)朋友拿到了商品,并把商品发了快递。
我是客户方,我要买手机!
我是你的朋友,即代理类,(事前处理)朋友选好了商品,准备把钱付给店家。
我是手机店老板,即目标类,你把钱给我就可以拿走你要的手机了!
我是你的朋友,即代理类,(事后处理)朋友拿到了商品,并把商品发了快递。

  (3)动态代理模式

  如果有N个目标类的话,代理类就会显得有很多重复的代码,会显得很冗长,而且代码的利用效率也不高。但是由于在代理类当中的事前处理和事后处理是一样,仅仅是目标类的不同,这个时候就可以使用动态代理模式。

  代码结构为:

  

  • 动态代理类:
 package bjtu.bigjunoba.dynamicProxy;

 import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method; public class DynamicProxy implements InvocationHandler { private Object subject; public DynamicProxy(Object subject) {
this.subject = subject;
} @Override
public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable {
System.out.println("我是你的朋友,即代理类,(事前处理)朋友选好了商品,准备把钱付给店家。");
arg1.invoke(subject, arg2);
System.out.println("我是你的朋友,即代理类,(事后处理)朋友拿到了商品,并把商品发了快递。");
return null;
} }
  • 客户类,调用构造动态代理类的实例,同时调用动态代理类的方法:
 package bjtu.bigjunoba.dynamicProxy;

 import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy; public class BuyerClient { public static void main(String[] args) { ShoesSeller shoesSeller = new ShoesSeller();
PhoneSeller phoneSeller = new PhoneSeller(); InvocationHandler shoeshandler = new DynamicProxy(shoesSeller);
InvocationHandler phonehandler = new DynamicProxy(phoneSeller); BuyShoes buyTheShoes = (BuyShoes) Proxy.newProxyInstance
(shoeshandler.getClass().getClassLoader(),shoesSeller.getClass().getInterfaces(), shoeshandler);
System.out.println("我想要买鞋子。");
buyTheShoes.BuyTheShoes(); System.out.println(); BuyPhone buyThePhone=(BuyPhone)Proxy.newProxyInstance
(phonehandler.getClass().getClassLoader(), phoneSeller.getClass().getInterfaces(),phonehandler);
System.out.println("我想要买手机。");
buyThePhone.BuyThePhone(); } }
  • 输出:
我想要买鞋子。
我是你的朋友,即代理类,(事前处理)朋友选好了商品,准备把钱付给店家。
我是鞋店老板,即目标类,你把钱给我就可以拿走你要的鞋了!
我是你的朋友,即代理类,(事后处理)朋友拿到了商品,并把商品发了快递。 我想要买手机。
我是你的朋友,即代理类,(事前处理)朋友选好了商品,准备把钱付给店家。
我是手机店老板,即目标类,你把钱给我就可以拿走你要的手机了!
我是你的朋友,即代理类,(事后处理)朋友拿到了商品,并把商品发了快递。

  InvocationHandler接口的invoke()方法:

 public class DynamicProxy implements InvocationHandler {

     @Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
return null;
}

  Proxy类的newProxyInstance()方法:

    public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
throws IllegalArgumentException
{
Objects.requireNonNull(h); final Class<?>[] intfs = interfaces.clone();
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
} final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if (!Modifier.isPublic(cl.getModifiers())) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
cons.setAccessible(true);
return null;
}
});
}
return cons.newInstance(new Object[]{h});
} catch (IllegalAccessException|InstantiationException e) {
throw new InternalError(e.toString(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString(), t);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString(), e);
}
}

  

  二、面向切面编程(AOP)

  在软件系统中,散布于应用中多处的功能被称为横切关注点。通常来讲,这些横切关注点从从概念上是与应用的业务逻辑相分离的(但是往往会直接嵌入到应用的业务逻辑之中)。把这些横切关注点与业务逻辑相分离正是面向切面编程所要解决的问题。

  简而言之,横切关注点可以被描述为影响应用多处的功能。

  

  例如,安全就是一个横切关注点,应用中的很多方法都会涉及到安全规则。上图展现了一个被划分为模块的典型应用。每个模块的核心功能都是为特定业务领域提供服务,但是这些模块都需要类似的辅助功能,例如安全和事务管理。

  如果要重用通用功能的话,最常见的面向对象技术是继承或委托。但是,如果在整个应用中都是用相同的基类,继承往往会导致一个脆弱的对象体系,而使用委托可能需要对委托对象进行复杂的调用。

  在使用面向切面编程时,仍然在一个地方定义通用功能,但是可以通过声明的方式定义这个功能要以何种方式在何处应用,而无需修改受影响的类。横切关注点可以被模块化为特殊的类,这些类被称为切面

  1.AOP各部分介绍

  

  (1)通知(Advice)

  切面的工作被称为通知。通知定义了切面是什么以及何时使用。除了描述切面要完成的工作,通知还解决了何时执行这个工作的问题。它应该在某个方法被调用之前?之后?之前和之后都调用?还是只在方法抛出异常时调用?

  Spring切面可以应用5种类型的通知:

  • 前置通知(Before):在目标方法被调用之前调用通知功能。
  • 后置通知(After):   在目标方法完成之后调用通知,此时不会关心方法的输出是什么。
  • 返回通知(After-returning):在目标方法成功执行之后调用通知。
  • 异常通知(After-throwing): 在目标方法抛出异常后调用通知。
  • 环绕通知(Around):通知包裹了被通知的方法,在被通知的方法调用之前和调用之后执行自定义的行为。

  (2)连接点(Join point)

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

  (3)切点(Poincut)

  一个切面并不需要通知应用的所有连接点。切点有助于缩小切面所通知的连接点的范围。如果说通知定义了切面的“什么”和“何时”的话,那么切点就定义了“何处”。切点的定义会匹配通知所要织入的一个或多个连接点。通常使用明确的类和方法名称,或是利用正则表达式定义所匹配的类和方法名称来指定这些切点。

  (4)切面(Aspect)

  切面是通知和切点的集合。通知和切点共同定义了切面的全部内容--它是什么,在何时和何处完成其功能。

  (5)引入(Introduction)

  引入允许我们向现有的类添加新方法或属性。新方法或属性被引入到现有的类中,可以在无需修改这些现有的类的情况下,让它们具有新的行为和状态。

  (6)织入(Weaving)

  织入是把切面应用到目标对象并创建新的代理对象的过程。切面在指定的连接点被织入到目标对象中。

  2.Spring对AOP的支持

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

  • 基于代理的经典Spring AOP
  • 纯POJO切面
  • @AspectJ注解驱动的切面
  • 注入式AspectJ切面(适用于Spring各版本)

  在了解了Spring对AOP的支持之后,还是以一些示例程序来理解实际是如何使用AOP的。还是以买鞋子买手机为例子,先给出下面的几个示例程序中都会用到的业务逻辑类:

  • 买鞋子接口:
 public interface BuyShoes {

     public void BuyTheShoes();
}
  • 买手机接口:
 public interface BuyPhone {

     public void BuyThePhone();
}
  • 实现了买鞋子接口的目标类:
 public class ShoesSeller implements BuyShoes {
@Override
public void BuyTheShoes() {
System.out.println("我是鞋店老板,即目标类,你把钱给我就可以拿走你要的鞋了!");
}
}
  • 实现了买手机接口的目标类:
 public class PhoneSeller implements BuyPhone {
@Override
public void BuyThePhone() {
System.out.println("我是手机店老板,即目标类,你把钱给我就可以拿走你要的手机了!");
}
}

  

  三、基于静态代理的经典AOP

  这种方式类似于静态代理模式,但是与静态代理模式不同的是,统一的事前处理和事后处理被单独地放在一个AOP当中的“通知类”当中,也就是说,不需要在代理类当中重写两个业务方法的时候重复写两遍事前处理和事后处理。这种方式需要XML配置,需要将目标类和增强类都注册到容器中,然后定义相应的切点,在根据切点和增强类结合定义切面,还需要定义代理,过程很繁琐,但是对于理解代理模式和AOP却是个很好的例子,虽然实际中不常用,但是可以牢记这个例子作为基础好好理解代理模式和基于代理的AOP。

  代码结构为:

  

  • 包含统一的事前处理和事后处理的BuyerHelper类:
 package bjtu.bigjunoba.proxyBased;

 import java.lang.reflect.Method;

 import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice; public class BuyerHelper implements AfterReturningAdvice, MethodBeforeAdvice { @Override
public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
System.out.println("我是你的朋友,即代理类,(事前处理)朋友选好了商品,准备把钱付给店家。");
} @Override
public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {
System.out.println("我是你的朋友,即代理类,(事后处理)朋友拿到了商品,并把商品发了快递。");
}
}

  BuyerHelper类实现了Spring框架的AOP部分的两个接口:AfterReturningAdvice接口和MethodBeforeAdvice接口,实现这两个接口之后需要重写两个方法,这两个方法就对应着事前处理和事后处理逻辑。

  从功能上来说,BuyerHelper类可以作为PhoneSeller和ShoesSeller两个类的增强类,可以扩展两个业务类的方法的功能,为两个业务类的方法提供统一的事前处理和事后处理。

  • Spring AOP的配置文件Spring-AOP.xml:
 <?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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" /> <context:annotation-config /> <!--对应bean注册入Spring -->
<bean id="buyerHelper" class="bjtu.bigjunoba.proxyBased.BuyerHelper"/>
<bean id="shoesSeller" class="bjtu.bigjunoba.proxyBased.ShoesSeller"/>
<bean id="phoneSeller" class="bjtu.bigjunoba.proxyBased.PhoneSeller"/> <!-- 定义切点,匹配所有的BuyTheshoes方法 -->
<bean id ="buyShoesPointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut">
<property name="pattern" value=".*BuyTheShoes"></property>
</bean> <!-- 定义切点,匹配所有的BuyThePhone方法 -->
<bean id ="buyPhonePointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut">
<property name="pattern" value=".*BuyThePhone"></property>
</bean> <!-- 定义一个基于Advisor的buyPhone 切面 = 通知 + 切点 -->
<bean id="buyPhoneHelperAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="advice" ref="buyerHelper"/>
<property name="pointcut" ref="buyPhonePointcut"/>
</bean> <!-- 定义一个基于Advisor的buyPhone 切面 = 通知 + 切点 -->
<bean id="buyShoesHelperAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="advice" ref="buyerHelper"/>
<property name="pointcut" ref="buyShoesPointcut"/>
</bean> <!-- 定义phoneSeller代理对象 -->
<bean id="buyPhoneProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="phoneSeller"/>
<property name="interceptorNames" value="buyPhoneHelperAdvisor"/>
</bean> <!-- 定义shoesSeller代理对象 -->
<bean id="buyShoesProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="shoesSeller"/>
<property name="interceptorNames" value="buyShoesHelperAdvisor"/>
</bean> </beans>

  配置文件主要分为以下几个部分:

  ①将目标类和代理类注册到Spring中并形成对应的bean:buyerHelper、shoesSeller、phoneSeller。

  ②根据正则表达式匹配两个业务类中的业务方法,即BuyTheShoes()方法和BuyThePhone()方法(可以看成接口中的方法,也可以看成实现了接口的目标类中的方法,但是最好是看成接口中的方法,因为这里是以接口中的方法来定义切面的),形成两个切点buyShoesPointcut和buyPhonePointcut。根据之前切点的定义,切点是定义了通知在“何处”被触发执行。就以切点buyShoesPointcut举例,当代码运行过程中如果运行到.BuyTheShoes这个方法的这个地方,Spring就知道可以触发通知了,然后就根据通知的定义,在.BuyTheShoes这个方法的执行前和执行后分别执行通知的具体方法。

  ③根据之前的定义我们可以理解到,通知定义了切面的“什么”和“何时”,而切点定义了切面的“何处”,所以说切面就是通知和切点的结合,也就是切面的全部内容就是在什么地方什么时候完成什么工作。这里是将两个切点和两个通知分别结合形成了两个切面buyPhoneHelperAdvisor和buyShoesHelperAdvisor。

  ④基于代理的经典Spring AOP就体现在要定义两个代理对象, 即buyPhoneProxy和buyShoesProxy。代理对象bean的形成是由目标业务类和对应的切面结合而成的。这两个代理对象去执行目标类方法的同时,还要根据切面的内容在合适的地点合适的时间执行合适的方法,也就是说“朋友”替“我”去做两件事“买鞋子”和“买衣服”。

  • 测试类ProxyBasedTest:
 package bjtu.bigjunoba.proxyBased;

 import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class ProxyBasedTest { public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext cfg = new ClassPathXmlApplicationContext("Spring-AOP.xml"); System.out.println("我要买手机!");
BuyPhone pSeller = cfg.getBean("buyPhoneProxy", BuyPhone.class);
pSeller.BuyThePhone(); System.out.println(); System.out.println("我要买鞋子!");
BuyShoes sSeller = cfg.getBean("buyShoesProxy", BuyShoes.class);
sSeller.BuyTheShoes();
}
}

  通过代理对象来执行业务方法,在执行业务方法的同时触发通知,从而在执行业务方法的事前和事后执行对应的增强方法。

  • 输出结果:
我要买手机!
我是你的朋友,即代理类,(事前处理)朋友选好了商品,准备把钱付给店家。
我是手机店老板,即目标类,你把钱给我就可以拿走你要的手机了!
我是你的朋友,即代理类,(事后处理)朋友拿到了商品,并把商品发了快递。 我要买鞋子!
我是你的朋友,即代理类,(事前处理)朋友选好了商品,准备把钱付给店家。
我是鞋店老板,即目标类,你把钱给我就可以拿走你要的鞋了!
我是你的朋友,即代理类,(事后处理)朋友拿到了商品,并把商品发了快递。

  

  四、自动配置代理将纯POJO转化为切面的AOP

  基于代理的经典Spring AOP在应对每一个不同的目标类的时候需要定义不同的代理去进行方法增强,这样会使得配置XML的时候显得很冗长。为了解决这个问题,可以让Spring去自动帮我们配置代理,而不再需要手动定义代理对象。

  这里你一定会有一个和我当时刚看的时候的疑问,为什么是从IoC容器中获取的是目标类的实例呢?而且最关键是为什么还能实现在切入点去调用增强类的方法呢?为此我也进行了一番调研,发现原来在使用DefaultAdvisorAutoProxyCreator的时候,这时候我们去调用getBean(“phoneSeller”),它其实给我们返回的是自动生成的AOP代理,而不是真实的phoneSeller这个目标类的实例。

  用这种方式去进行AOP的实现,可以说比第一种方式来的好方便很多,但是也有可能造成一定的不便。如我们需要在代码中调用到原始的目标类,那这时候我们就没办法再从Spring容器当中去获取了,应为通过getBean方法去获取的话,返回的是AOP代理。

  代码结构为:

  

  • 包含统一的事前处理和事后处理的BuyerHelper类:
 package bjtu.bigjunoba.AutoScanAdvisor;

 import java.lang.reflect.Method;

 import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice; public class BuyerHelper implements AfterReturningAdvice, MethodBeforeAdvice { @Override
public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
System.out.println("我是你的朋友,即代理类,(事前处理)朋友选好了商品,准备把钱付给店家。");
} @Override
public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {
System.out.println("我是你的朋友,即代理类,(事后处理)朋友拿到了商品,并把商品发了快递。");
}
}
  • Spring AOP的配置文件Spring-AOP.xml:
 <?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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" /> <context:annotation-config /> <!--对应bean注册入Spring -->
<bean id="buyerHelper" class="bjtu.bigjunoba.AutoScanAdvisor.BuyerHelper"/>
<bean id="shoesSeller" class="bjtu.bigjunoba.AutoScanAdvisor.ShoesSeller"/>
<bean id="phoneSeller" class="bjtu.bigjunoba.AutoScanAdvisor.PhoneSeller"/> <!-- 定义切点,匹配所有的BuyTheshoes方法 -->
<bean id ="buyShoesPointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut">
<property name="pattern" value=".*BuyTheShoes"></property>
</bean>
<!-- 定义切点,匹配所有的BuyTheshoes方法 -->
<bean id ="buyPhonePointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut">
<property name="pattern" value=".*BuyThePhone"></property>
</bean> <!-- 定义一个基于Advisor的buyPhone切面 = 通知+切点结合 -->
<bean id="buyPhoneHelperAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="advice" ref="buyerHelper"/>
<property name="pointcut" ref="buyPhonePointcut"/>
</bean> <!-- 定义一个基于Advisor的buyPhone切面 = 通知+切点结合 -->
<bean id="buyShoesHelperAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="advice" ref="buyerHelper"/>
<property name="pointcut" ref="buyShoesPointcut"/>
</bean> <!-- 自动扫描配置文件中的Advisor,并且去匹配其对应的实现切入点拦截方法接口的目标类 -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>
</beans>

  其中第47行配置就是自动扫描Spring中的所有的切面,然后根据切点匹配规则将切面和目标业务类匹配起来,从而让Spring实现自动代理。利用DefaultAdvisorAutoProxyCreator去扫描Spring配置文件当中的Advisor,并且为每一个Advisor匹配对应实现了切点拦截方法的业务接口的实现类。比如,buyShoesHelperAdvisor切面中,切点buyPhonePointcut的拦截方法是BuyThePhone(),那么Spring会自动匹配究竟有那个类去实现了声明了BuyThePhone()方法的接口,就找到了phoneSeller这个简单Java Bean(如果还有其他的类实现了这个方法的业务接口,也会一起被代理),并且自动为其配置代理。

  • 测试类AutoScanAdvisorTest:
 package bjtu.bigjunoba.AutoScanAdvisor;

 import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class AutoScanAdvisorTest { public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext cfg = new ClassPathXmlApplicationContext("Spring-AOP.xml"); System.out.println("我要买手机!");
BuyPhone pSeller = cfg.getBean("phoneSeller", BuyPhone.class);
pSeller.BuyThePhone(); System.out.println(); System.out.println("我要买鞋子!");
BuyShoes sSeller = cfg.getBean("shoesSeller", BuyShoes.class);
sSeller.BuyTheShoes();
}
}

  这里的不同之处在于,getBean()方法的参数只需要设置目标类POJO(简单JavaBean)就可以实现将目标业务类和对应切面相互关联,而不用再定义代理对象。

  • 输出结果为:
我要买手机!
我是你的朋友,即代理类,(事前处理)朋友选好了商品,准备把钱付给店家。
我是手机店老板,即目标类,你把钱给我就可以拿走你要的手机了!
我是你的朋友,即代理类,(事后处理)朋友拿到了商品,并把商品发了快递。 我要买鞋子!
我是你的朋友,即代理类,(事前处理)朋友选好了商品,准备把钱付给店家。
我是鞋店老板,即目标类,你把钱给我就可以拿走你要的鞋了!
我是你的朋友,即代理类,(事后处理)朋友拿到了商品,并把商品发了快递。

  

  五、基于@AspectJ注解驱动的AOP

  回顾一下将纯POJO转化为切面方式的XML配置,会发现相比较于基于代理方式,XML配置文件并没有简化多少,反正看起来还是很复杂。于是基于@AspectJ注解的形式的优点就可以显现出来了,这种形式比让Spring进行自动代理看起来更舒服更简单一些,只用掌握几个简单的注解使用方法就可以灵活运用这种方式。

  但是这种方式的问题还是同样的:可以看到和之前一样,我们通过获取PhoneSeller和ShoesSeller的实例,Spring会给我们自动返回他们的代理对象,然后通过他们的代理对象去调用相应方法的接口,实现目标类的方法的增强,效果与其他方式一致。

  学到这里,看到基于注解这几个字,突然就想起了之前已经学习过的《装配Bean》里面的自动配置方式,通过注解将POJO类都声明为Spring中的组件,然后通过Java或者xml开启组件扫描,就不用再在xml里面再进行注册bean这一些操作,这样我们的xml的配置就更加更加的简化了。于是在这里就采用了这种方法,在xml中开启组件扫描,这个时候又会想,我干脆就不想要这个什么xml配置文件了可以不,当然可以。

  代码结构为:

  

  • (切面类通知类)包含统一的事前处理和事后处理的BuyerHelper类:
 package bjtu.bigjunoba.annotationBased1;

 import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component; @Aspect
@Component("BuyerHelperAspect")
public class BuyerHelper { @Pointcut("execution(* bjtu.bigjunoba.annotationBased1.*.*(..))")
public void BuySomething() {
} @Before("BuySomething()")
public void before() {
System.out.println("我是你的朋友,即代理类,(事前处理)朋友选好了商品,准备把钱付给店家。");
} @AfterReturning("BuySomething()")
public void after() {
System.out.println("我是你的朋友,即代理类,(事后处理)朋友拿到了商品,并把商品发了快递。");
}
}

  切面类是基于注解的AOP的最重要的一个类:

  ①BuyerHelper类使用@Aspect注解进行了标注,该标注表明BuyerHelper类是一个切面,回顾一下之前学习过的内容:切面=切点+通知,再看BuyerHelper类,果然是这样。

  ②BuyerHelper类还使用了@Component注解进行了标注,表明BuyerHelper类是一个POJO,如果开启组件扫描的话,就可以把BuyerHelper类注册成bean到Spring当中。

  ③BuySomething()方法使用@Pointcut注解进行了标注,首先解释一下切点表达式:

@Pointcut("execution(* bjtu.bigjunoba.annotationBased1.*.*(..))")
这是一个切点表达式:
execution()指示器:在方法执行时触发。
*:返回值的类型为任意类型。
bjtu.bigjunoba.annotationBased1.*.*(..):用正则表达式来表示bjtu.bigjunoba.annotationBased1包下的任意类的任意方法都作为切点

  假如方法before是带参数的,可以使用下面的表示方法传递参数:

@Pointcut("execution(* bjtu.bigjunoba.annotationBased1.*.*(..))"
+ "&& args(参数1, 参数2)")
public void before(类型1 参数1,类型2 参数2) {
...
}

  如果不在BuySomething()方法上使用@Pointcut注解的话,那么就要将通知的两个注解都改成切点表达式,即

@Aspect
@Component("BuyerHelperAspect")
public class BuyerHelper { @Before("execution(* bjtu.bigjunoba.annotationBased1.*.*(..))")
public void before() {
System.out.println("我是你的朋友,即代理类,(事前处理)朋友选好了商品,准备把钱付给店家。");
} @AfterReturning("execution(* bjtu.bigjunoba.annotationBased1.*.*(..))")
public void after() {
System.out.println("我是你的朋友,即代理类,(事后处理)朋友拿到了商品,并把商品发了快递。");
}
}

  这样表达也可以,但是假设有N个不同的处理类,那就要将相同的切点表达式重复N遍,这样就会显得很繁琐。解决办法就是,只定义这个切点一次,然后每次需要的时候引用它,这里通过在BuySomething()方法上使用@Pointcut注解扩展了切点表达式语言,这样就可以在任何切点表达式中使用BuySomething()方法了。BuySomething()方法的实际内容并不重要,在这里它实际上应该是空的, 其实该方法本身只是一个标识,供@Pointcut注解依附。

  ④事前处理方法before()和事后处理方法after()。

  • Spring AOP的配置文件Spring-AOP.xml:
<?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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" /> <context:annotation-config /> <!-- 扫描包 -->
<context:component-scan base-package="bjtu.bigjunoba.annotationBased1" annotation-config="true"/> <!-- ASPECTJ注解 -->
<aop:aspectj-autoproxy proxy-target-class="true" /> <!-- 目标类 -->
<bean id="phoneSeller" class="bjtu.bigjunoba.annotationBased1.PhoneSeller"/>
<bean id="shoesSeller" class="bjtu.bigjunoba.annotationBased1.ShoesSeller"/> </beans>

  ①开启组件扫描,扫描包中所有带有@Component注解的组件类,并在Spring中注册成JavaBean。

  ②<aop:aspectj-autoproxy />用来启用AspectJ自动代理, 启用之后,AspectJ会为使用@Aspect注解的bean创建一个代理,这个代理会围绕着所有该切面的切点所匹配的bean。需要注意的是,Spring的AspectJ自动代理仅仅使用@AspectJ作为创建切面的指导,切面依然是基于代理的。在本质上,它依然是Spring基于代理的切面,这意味着,尽管使用的是@AspectJ注解,但我们仍然限于代理方法的调用。当然也可以在JavaConfig中启用AspectJ注解的自动代理,这个在后面会提到。

  • 测试类AnnotationBasedTest(注意文件路径):
 package bjtu.bigjunoba.annotationBased1;

 import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class AnnotationBasedTest { public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext cfg = new ClassPathXmlApplicationContext("classpath:bjtu/bigjunoba/annotationBased1/AnnotationBased1.xml"); System.out.println("我要买手机!");
BuyPhone pSeller = cfg.getBean("phoneSeller", BuyPhone.class);
pSeller.BuyThePhone(); System.out.println(); System.out.println("我要买鞋子!");
BuyShoes sSeller = cfg.getBean("shoesSeller", BuyShoes.class);
sSeller.BuyTheShoes();
}
}

  针对这种方式,还有一些变体:

  1. 将目标类使用@Component注解,同时不用再在XML配置中定义目标类bean,在测试类中通过读取XML配置文件。
  • 添加@Component注解到目标类PhoneSeller中:
 package bjtu.bigjunoba.annotationBased2;

 import org.springframework.stereotype.Component;

 @Component("phoneSeller")
public class PhoneSeller implements BuyPhone { @Override
public void BuyThePhone() {
System.out.println("我是手机店老板,即目标类,你把钱给我就可以拿走你要的手机了!");
}
}
  • 添加@Component注解到目标类ShoesSeller中:
 package bjtu.bigjunoba.annotationBased2;

 import org.springframework.stereotype.Component;

 @Component("shoesSeller")
public class ShoesSeller implements BuyShoes { @Override
public void BuyTheShoes() {
System.out.println("我是鞋店老板,即目标类,你把钱给我就可以拿走你要的鞋了!");
}
}
  • 删除目标类注册bean的XML配置文件:
 <?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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" /> <context:annotation-config /> <!--扫描包 -->
<context:component-scan base-package="bjtu.bigjunoba.annotationBased2" annotation-config="true"/> <!-- ASPECTJ注解 -->
<aop:aspectj-autoproxy proxy-target-class="true" /> </beans>
  • 读取配置文件获取通过@Component注解的bean的测试类:
 package bjtu.bigjunoba.annotationBased2;

 import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class AnnotationBasedTest { public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext cfg = new ClassPathXmlApplicationContext("classpath:bjtu/bigjunoba/annotationBased2/AnnotationBased2.xml"); System.out.println("我要买手机!");
BuyPhone pSeller = (BuyPhone) cfg.getBean("phoneSeller");
pSeller.BuyThePhone(); System.out.println(); System.out.println("我要买鞋子!");
BuyShoes sSeller = (BuyShoes) cfg.getBean("shoesSeller");
sSeller.BuyTheShoes();
}
}

  2.不使用XML配置文件,直接使用JavaConfig开启自动扫描和AspectJ自动代理。

  代码结构为:

  

  • JavaConfig核心配置类:
package bjtu.bigjunoba.annotationBased3;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy; @Configuration
@EnableAspectJAutoProxy
@ComponentScan
public class AnnotationBased3Config { }
  • 读取核心配置类的测试类:
package bjtu.bigjunoba.annotationBased3;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.ContextConfiguration; @ContextConfiguration(classes = AnnotationBased3Config.class)
public class AnnotationBasedTest { public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext cfg = new AnnotationConfigApplicationContext(AnnotationBased3Config.class); System.out.println("我要买手机!");
BuyPhone pSeller = (BuyPhone) cfg.getBean("phoneSeller");
pSeller.BuyThePhone(); System.out.println(); System.out.println("我要买鞋子!");
BuyShoes sSeller = (BuyShoes) cfg.getBean("shoesSeller");
sSeller.BuyTheShoes(); }
}

  

  六、基于XML配置的AOP

  如果需要声明切面,但是又不能为通知类添加注解的时候,就必须要使用XML配置了。

  代码结构为:

  

  • 取出@Aspect注解的通知类BuyerHelper(但是还是要通过@Service注解将通知类当成业务bean注册到Spring中):
 package bigjun.bjtu.XMLBased;

 import org.springframework.stereotype.Service;

 @Service("BuyerHelper")
public class BuyerHelper { public void before() {
System.out.println("我是你的朋友,即代理类,(事前处理)朋友选好了商品,准备把钱付给店家。");
} public void after() {
System.out.println("我是你的朋友,即代理类,(事后处理)朋友拿到了商品,并把商品发了快递。");
}
}
  • 通过XML配置声明切面的配置文件XMLBased.xml:
 <?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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" /> <context:annotation-config /> <!--扫描包 -->
<context:component-scan base-package="bigjun.bjtu.XMLBased" annotation-config="true"/> <aop:config>
<aop:aspect ref="BuyerHelper">
<aop:before method="before" pointcut="execution(* bigjun.bjtu.XMLBased.*.*(..))"/>
<aop:after method="after" pointcut="execution(* bigjun.bjtu.XMLBased.*.*(..))"/>
</aop:aspect>
</aop:config> </beans>

  ①ref="BuyerHelper引用了一个POJO bean,该bean实现了切面的功能,在这里就是BuyerHelper bean,BuyerHelper bean提供了在切面中通知所调用的before()方法和after()方法

  ②pointcut属性定义了通知所应用的切点,它的值是使用AspectJ切点表达式语法所定义的切点。

  ③就像是基于注解的AOP使用@Pointcut注解来消除重复的内容一样,在基于XML的切面声明中,也可以使用<aop:pointcut>元素,比如可以将XMLBased.xml修改成:

 <?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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" /> <context:annotation-config /> <!--扫描包 -->
<context:component-scan base-package="bigjun.bjtu.XMLBased" annotation-config="true"/> <aop:config>
<aop:aspect ref="BuyerHelper">
<aop:pointcut id="BuySomething" expression="execution(* bigjun.bjtu.XMLBased.*.*(..))"/>
<aop:before method="before" pointcut-ref="BuySomething"/>
<aop:after method="after" pointcut-ref="BuySomething"/>
</aop:aspect>
</aop:config> </beans>
  • 测试类和输出结果没有变化

  

  七、AOP中五种通知Advice的使用

  首先回顾一下五种通知:

  • @After               (后置通知):通知方法会在目标方法返回或抛出异常后调用
  • @AfterReturning(返回通知):通知方法会在目标方法返回后调用
  • @AfterThrowing(异常通知):通知方法会在目标方法抛出异常后调用
  • @Around           (环绕通知):通知方法将目标方法封装起来
  • @Before           (前置通知):通知方法会在目标方法调用之前执行

  然后以包含五种通知的代码来理解一下这5种通知的使用:

  代码结构为:

  

  • 目标方法接口:
 package bigjun.bjtu.fiveAdvices;

 public interface AdviceTypeITF {

     public String Method1(String name);
public void Method2(String name, String id);
}
  • 实现目标方法接口并且包含两个目标方法的目标类:
 package bigjun.bjtu.fiveAdvices;

 import org.springframework.stereotype.Component;

 @Component("adviceType")
public class AdviceType implements AdviceTypeITF { @Override
public String Method1(String name) {
System.out.println("方法1的输出");
return "方法1的返回值";
} @Override
public void Method2(String name, String id) {
System.out.println("方法2的输出");
} }
  • 包含五种通知的切面类:
package bigjun.bjtu.fiveAdvices;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component; @Aspect
@Component("Aspect")
public class FiveAdviceAspect { @Pointcut("execution(* bigjun.bjtu.fiveAdvices.*.*(..))")
public void DoSomething() {
} @Before("DoSomething()")
public void before(JoinPoint joinpoint)
{
System.out.print("这是前置通知 : ");
for (int i = 0; i < joinpoint.getArgs().length; i++) {
System.out.print(joinpoint.getArgs()[i]+" ");
}
System.out.println(joinpoint.getSignature().getName());
} @After("DoSomething()")
public void after(JoinPoint joinpoint)
{
System.out.print("这是后置通知 : ");
for (int i = 0; i < joinpoint.getArgs().length; i++) {
System.out.print(joinpoint.getArgs()[i]+" ");
}
System.out.println(joinpoint.getSignature().getName());
} @AfterReturning(pointcut="DoSomething()",returning="result")
public void afterReturning(JoinPoint jointpoint ,String result)
{
System.out.print("这是返回通知 : "+"result= "+result+" ");
for (int i = 0; i < jointpoint.getArgs().length; i++) {
System.out.print(jointpoint.getArgs()[i]+" ");
}
System.out.println(jointpoint.getSignature().getName());
} @AfterThrowing(pointcut="DoSomething()",throwing="e")
public void exception(Exception e)
{
System.out.println("这是异常通知 : "+e);
} @Around("DoSomething()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable
{
//可以在环绕通知之下进行权限判断
System.out.print("这是环绕通知 : ");
for (int i = 0; i < pjp.getArgs().length; i++) {
System.out.print(pjp.getArgs()[i]+" ");
}
System.out.println(pjp.getSignature().getName());
System.out.println("proceed()方法执行前");
Object result=pjp.proceed();
System.out.println("proceed()方法执行后");
return result; }
}
  • 开启组件扫描和AspectJ自动代理的XML配置文件:
 <?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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" /> <context:annotation-config /> <!--扫描包 -->
<context:component-scan base-package="bigjun.bjtu.fiveAdvices" annotation-config="true"/>
<!-- ASPECTJ注解 -->
<aop:aspectj-autoproxy proxy-target-class="true" /> </beans>
  • 测试类:
 package bigjun.bjtu.fiveAdvices;

 import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class FiveAdvicesTest { public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext cfg = new ClassPathXmlApplicationContext("FiveAdvices.xml"); AdviceType aType = cfg.getBean("adviceType", AdviceType.class); System.out.println("我要运行方法1!");
aType.Method1("来自方法1的QiaoJiang"); System.out.println(); System.out.println("我要运行方法2!");
aType.Method2("来自方法2的LianJiang", "No.2"); }
}
  • 输出结果:
我要运行方法1!
这是环绕通知 : 来自方法1的QiaoJiang Method1
proceed()方法执行前
这是前置通知 : 来自方法1的QiaoJiang Method1
方法1的输出
proceed()方法执行后
这是后置通知 : 来自方法1的QiaoJiang Method1
这是返回通知 : result= 方法1的返回值 来自方法1的QiaoJiang Method1 我要运行方法2!
这是环绕通知 : 来自方法2的LianJiang No.2 Method2
proceed()方法执行前
这是前置通知 : 来自方法2的LianJiang No.2 Method2
方法2的输出
proceed()方法执行后
这是后置通知 : 来自方法2的LianJiang No.2 Method2

  从输出结果可以看出,前置,后置,返回,异常都一目了然,然而需要重点分析一下环绕通知。

    @Around("DoSomething()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable
{
//可以在环绕通知之下进行权限判断
System.out.print("这是环绕通知 : ");
for (int i = 0; i < pjp.getArgs().length; i++) {
System.out.print(pjp.getArgs()[i]+" ");
}
System.out.println(pjp.getSignature().getName());
System.out.println("proceed()方法执行前");
Object result=pjp.proceed();
System.out.println("proceed()方法执行后");
return result;
}

  环绕通知是最为强大的通知类型,它能够让你所编写的逻辑将被通知的目标方法完全包装起来。实际上就像在一个通知方法中同时编写好多通知。示例中需要注意的是,环绕通知的返回值就是目标方法的返回值。

  写一个伪代码就很好理解了:

    @Around("DoSomething()")
public void aroundAdviceTest(ProceedingJoinPoint jp) {
try {
前置通知代码块
jp.proceed();
返回通知代码块
后置通知代码块
} catch (Throwable e) {
异常通知代码块
}
}

  环绕通知的通知方法必须接受ProceedingJoinPoint作为参数,这个对象是必须要有的,因为米要在通知中通过它来调用被通知的方法。通知方法中可以做任何的事情,当要将控制权交给被通知的方法时,需要调用ProceedingJoinPoint的proceed()方法。如果不调用这个方法的话,会阻塞对被通知方法的访问。

  八、AOP的概念和使用原因

  现实中有一些内容并不是面向对象(OOP)可以解决的,必须数据库事务,它对于企业级的Java EE应用而言是十分重要的,又如在电商网站购物需要经过交易系统、财务系统,对于交易系统存在一个交易记录的对象,而财务系统则存在账户的信息对象。从这个角度而言,需要对交易记录和账户操作形成一个统一的事务管理。交易和账户的事务,要么全部成功,要么全部失败。

  

  交易记录和账户记录都是对象,这两个对象需要在同一个事务中控制,这就不是面向对象可以解决的问题,而需要用到面向切面的编程,这里的切面环境就是数据库事务。

  AOP编程有着重要的意义,首先它可以拦截一些方法,然后把各个对象组织成一个整体,比如网站的交易记录需要记录日志,如果约定好了动态的流程,就可以在交易前后、交易正常完成后或者交易异常发生时,通过这些约定记录相关的日志了。

  在JDBC的代码中,需要考虑try...catch...finally语句和数据库资源的关闭问题,而且这些代码会存在大量重复。

  

  AOP是通过动态代理技术,来管控各个对象操作的切面环境,管理包括日志、数据库事务等操作,让我们拥有可以在反射原有对象方法之前正常返回、异常返回事后插入自己的逻辑代码的能力,有时候甚至取代原始方法。在一些常用的流程中,比如数据库事务,AOP会提供默认的实现逻辑,也会提供一些简单的配置,程序员就可以比较方便地修改默认的实现,达到符合真实应用的效果,这样就就可以大大降低开发的工作量,提高代码的可读性和可维护性,将开发集中在业务逻辑上。

  

  九、多个切面

  多个切面的情况下,执行顺序是无序的,可以使用@Order(1)、@Order(2)、@Order(3)为其添加执行顺序.

@Aspect
@Order(1)
public class Aspect1 {
...
}
@Aspect
@Order(2)
public class Aspect2 {
...
}
@Aspect
@Order(3)
public class Aspect3 {
...
}

  示例程序源代码已上传至GitHub:https://github.com/BigJunOba/SpringAOP

Spring(三)面向切面编程(AOP)的更多相关文章

  1. Spring(4)——面向切面编程(AOP模块)

    Spring AOP 简介 如果说 IoC 是 Spring 的核心,那么面向切面编程就是 Spring 最为重要的功能之一了,在数据库事务中切面编程被广泛使用. AOP 即 Aspect Orien ...

  2. 04 Spring:01.Spring框架简介&&02.程序间耦合&&03.Spring的 IOC 和 DI&&08.面向切面编程 AOP&&10.Spring中事务控制

    spring共四天 第一天:spring框架的概述以及spring中基于XML的IOC配置 第二天:spring中基于注解的IOC和ioc的案例 第三天:spring中的aop和基于XML以及注解的A ...

  3. Spring学习手札(二)面向切面编程AOP

    AOP理解 Aspect Oriented Program面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术. 但是,这种说法有些片面,因为在软件工程中,AOP的价值体现的并 ...

  4. Spring IOP 面向切面编程

    Spring IOP  面向切面编程 AOP操作术语 Joinpoint(连接点):所谓连接点是指那些被拦截到的点.在spring中,这些点指的是方法,因为spring只支持方法类型的连接点.(类里面 ...

  5. Spring学习笔记:面向切面编程AOP(Aspect Oriented Programming)

    一.面向切面编程AOP 目标:让我们可以“专心做事”,避免繁杂重复的功能编码 原理:将复杂的需求分解出不同方面,将公共功能集中解决 *****所谓面向切面编程,是一种通过预编译方式和运行期动态代理实现 ...

  6. Spring框架学习笔记(2)——面向切面编程AOP

    介绍 概念 面向切面编程AOP与面向对象编程OOP有所不同,AOP不是对OOP的替换,而是对OOP的一种补充,AOP增强了OOP. 假设我们有几个业务代码,都调用了某个方法,按照OOP的思想,我们就会 ...

  7. Spring框架系列(4) - 深入浅出Spring核心之面向切面编程(AOP)

    在Spring基础 - Spring简单例子引入Spring的核心中向你展示了AOP的基础含义,同时以此发散了一些AOP相关知识点; 本节将在此基础上进一步解读AOP的含义以及AOP的使用方式.@pd ...

  8. Spring之控制反转——IoC、面向切面编程——AOP

      控制反转——IoC 提出IoC的目的 为了解决对象之间的耦合度过高的问题,提出了IoC理论,用来实现对象之间的解耦. 什么是IoC IoC是Inversion of Control的缩写,译为控制 ...

  9. 面向切面编程(Aop)

    AOP中的概念 AOP(Aspect Orient Programming),也就是面向切面编程.可以这样理解,面向对象编程(OOP)是从静态角度考虑程序结构,面向切面编程(AOP)是从动态角度考虑程 ...

  10. 利用例子来理解spring的面向切面编程

    最近学习了spring的面向切面编程,在网上看到猴子偷桃的例子,觉得这种方式学习比书本上讲解有趣多了,也便于理解.现在就来基于猴子偷桃写个基本的例子. maven工程:

随机推荐

  1. C++进程间通讯方式

    1.剪切板模式. 在MFC里新建两个文本框和两个按钮,点击发送按钮相当于复制文本框1的内容,点击接收按钮相当于粘贴到文本框2内: 发送和接收按钮处功能实现如下: void CClipboard2Dlg ...

  2. SSH Config 管理多主机

    使用 一般我们使用ssh连接远程主机的时候,使用命令是: ssh root@ip ssh –i [identity-file] -p [port] user@hostname 但是如果ip地址过多,其 ...

  3. 教你用开源 JS 库快速画出 GitHub 章鱼猫

    本文作者:HelloGitHub-kalifun 在上一篇文章我们介绍了 Zdog 如何使用,接下来这篇文章我将带领各位利用 Zdog 画出一个 GitHub 章鱼猫(和官方的还是有些差别的). Zd ...

  4. 死磕 java同步系列之mysql分布式锁

    问题 (1)什么是分布式锁? (2)为什么需要分布式锁? (3)mysql如何实现分布式锁? (4)mysql分布式锁的优点和缺点? 简介 随着并发量的不断增加,单机的服务迟早要向多节点或者微服务进化 ...

  5. Flask基础(03)-->创建第一个Flask程序

    # 导入Flask from flask import Flask # 创建Flask的应用程序 # 参数__name__指的是Flask所对应的模块,其决定静态文件从哪个地方开始寻找 app = F ...

  6. RocketMQ 源码学习笔记 Producer 是怎么将消息发送至 Broker 的?

    目录 RocketMQ 源码学习笔记 Producer 是怎么将消息发送至 Broker 的? 前言 项目结构 rocketmq-client 模块 DefaultMQProducerTest Roc ...

  7. ELK日志分析系统(3)-logstash数据处理

    1. 概述 logspout收集数据以后,就会把数据发送给logstash进行处理,本文主要讲解logstash的input, filter, output处理 2. input 数据的输入处理 支持 ...

  8. 创建一个 Laravel 项目

    创建一个 Laravel 项目,首先需要安装 Composer ,如果没有安装的参考 https://docs.phpcomposer.com/00-intro.html 一.安装 Laravel 安 ...

  9. 05-03 主成分分析(PCA)

    目录 主成分分析(PCA) 一.维数灾难和降维 二.主成分分析学习目标 三.主成分分析详解 3.1 主成分分析两个条件 3.2 基于最近重构性推导PCA 3.2.1 主成分分析目标函数 3.2.2 主 ...

  10. GUI tkinter (Menu)菜单项篇

    """添加顶层菜单:1.我们可以使用Menu类来新建一个菜单,Menu和其他的组件一样,第一个是parent,这里通常可以为窗口2.然后我们可以用add_command方 ...