[Spring实战系列] - No.3 Spring Aop编程与AspectJ

在本篇文章,我们讲解什么叫AOP以及AOP在Spring中应用的方法。那么什么叫AOP呢?AOP为Aspect Oriented
Programming的缩写,意为:面向切面编程。听到这个名词,你可能会非常的困惑,什么叫面向切面编程呢?我们来回
顾一下在《Spring实战》中的一个例子。Knight(骑士)类和Minstrel(吟唱诗人)类之间有一个关系是,骑士每次经历一次
战斗,就会有一个吟唱诗人给他作诗歌颂。那么我们的骑士类和诗人之间是什么关系呢?需要每个骑士类内部包含一个
诗人,然后其实调用写诗的功能么?事实上,骑士并不知道诗人为他写诗,同时,诗人也不属于任何骑士,诗人为所有
骑士写诗。那么我们该怎么实现这个功能呢?这里我们就应用到了AOP编程,即面向切面编程。
想象一下,如果有一个诗人,以某种方式“包裹”了骑士(或者说覆盖在了骑士外边),在骑士每次进行战斗后(或前),

就会得知骑士战斗的消息,这样是不是就符合我们的需求了?这里,那个诗人就是我们需要的切面。

那么回到我们的AOP编程上,我们来分析一下AOP的架构以及其中的术语:

1.通知(Advice): AOP中,切面的功能被称为通知。通知定义了切面的功能以及何时被使用,它应该在方法调用 之前?之后?或者抛出异常时?
2.连接点(Joinpoint):程序可能有很多很多时机可以应用通知,这些时机被称为是“连接点”。连接点是在程序执
行过程中能够插入切面的一个点。
3.切入点(Pointcut):切入点的定义匹配通知要织入一个或多个连接点。切入点定义了“何地”应用通知。比如一个
程序会可能有很多函数,我们只在某个函数应用时,才应用通知。这就是切入点。
4.切面(Aspect):切面是切入点和通知的结合,他们共同定义了切面的功能,以及何时何地被应用。
5.引入(Introduction):引入允许我们向现有的类添加新方法或属性,从而可以在无需修改现有类的情况下,让它
们具有新的行为和状态。
6.目标(Target):被通知的对象
7.代理(Proxy):”代理“是向目标对象应用通知以后被创建的对象。可以和织入(Weaving)配合理解。
8.织入(Weaving):”织入“是把切面应用到目标对象来创建新的代理对象的过程。
下面我们来看如何创建一个经典的Spring切面:
还记得我们之前的例子么?在这里我们增加一个观众来对表演进行反馈。同时,我们应用上面所说的模式,把观
众做成一个切面。

首先创建观众类:

public class Audience {
    public Audience(){}
    public void takeSeats(){
        System.out.println("I'm taking seat");
    }

    public void turnOffPhone(){
        System.out.println("I'm turing off my phone");
    }


    public void applaud(){
        System.out.println("Claping...PA PA PA PA PA PA PA PA");
    }

 
    public void demandRefund(){
        System.out.println("Boo! I want my money back!");
    }
}

然后,我们创建一个观众服务:

public class AudienceAdvice  implements MethodBeforeAdvice,AfterReturningAdvice,ThrowsAdvice{
    private Audience audience;
    public AudienceAdvice(){}

    public void before(Method method,Object[]args,Object target) throws Throwable{
            audience.takeSeats();
            audience.turnOffPhone();
    }

    public void afterReturning(Object returnValue,Method method,Object[]args,Object target) throws Throwable{
        audience.applaud();
    }

    public void afterThrowing(Throwable throwable){
        audience.demandRefund();
    }

    public void setAudience(Audience audience){
        this.audience = audience;
    }
}

那么在哪里使用这些通知呢?我们来定义切点和通知者:

<bean id="performancePointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut">
     <property name="pattern" value=".*perform"></property>
</bean>
<bean id="audienceAdvice" class="AudienceAdvice">
     <property name="audience" ref="audience"></property>
</bean>
<bean id="audienceAdvisor" class="org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor">
     <property name="advice" ref="audienceAdvice"></property>
     <property name="pointcut" ref="performancePointcut"></property>
</bean>

当然我们也可以使用AspectJ的切点

        <bean id="audienceAdvisor"
              class="org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor">
              <property name="advice" ref="audienceAdvice"></property>
                <property name="expression" value="execution(* *.perform(..))"></property>
        </bean>

我们已经把切点,通知者都定义好了,接下来就要创建代理了:

        <bean id="sonnet29" class="Sonnet29"></bean>
        <bean id="dukeTarget"
              class="PoeticJuggler"
              autowire="constructor">
                <constructor-arg ref="sonnet29"></constructor-arg>
        </bean>
        <bean id="duke"
              class="org.springframework.aop.framework.ProxyFactoryBean">
                <property name="target" ref="dukeTarget"></property>
                <property name="interceptorNames" value="audienceAdvisor"></property>
                <property name="proxyInterfaces" value="Performer"></property>
        </bean>-->

这样一来,代理也实现了。到此,一个切面就完成了。你有没有觉得这样非常的复杂呢?是的!上面的过程虽然
创建步骤很清晰,但是太冗长了。我们该怎么更好的使用切面呢?答案很简单。我们使用自动代理的@AspecJ切面。

一切回到原点。删掉你刚刚在intellij中敲的代码,回到我们的audience。按照下面,把audience注解为切面:

/**
 * Created by YanMing on 2017/2/21.
 */
import org.aspectj.lang.annotation.*;

@Aspect
public class Audience {
    public Audience(){}

    @Pointcut("execution(* *.perform(..))")
    public void performance(){}

    @Before("performance()")
    public void takeSeats(){
        System.out.println("I'm taking seat");
    }

   @Before("performance()")
    public void turnOffPhone(){
        System.out.println("I'm turing off my phone");
    }

   @AfterReturning("performance()")
    public void applaud(){
        System.out.println("Claping...PA PA PA PA PA PA PA PA");
    }

   @AfterThrowing("performance()")
    public void demandRefund(){
        System.out.println("Boo! I want my money back!");
    }
}

我们来解释一下上面的代码,按照切面-切点-通知的顺序来。首先切面就是我们的Audience类啦,因为我们使用
了@Aspect注解,将该类注解为一个切面。接下来切点就是我们Pointcut那两行。我们将凡是有执行*.perform()的地方
都定义为切点,并且以performance()函数进行标记,我们将会在这里应用通知。接下来,通知就是下面的四种函数。同
时,我们用注解标记了函数,声明了通知的何时使用。

这样就好了么?你是不是发现,我们并没有实现代理?对的。我们使用自动代理,只需要在aop.xml中这样写道:

<aop:aspectj-autoproxy/>

那么简短!快来试试我们的代码吧!像我们前面那样写单元测试。运行结果如下:


这种注解的方式要求,我们必须对源码进行操作。如果我们无法操作通知(audience)的具体代码是无法实现的。那
如果凑巧我们无法接触到源码,只知道其中的函数该怎么办呢?那么我们可以在aop.xml中,定义纯粹的POJO切面

在你的aop.xml中这么写,可以取代你以上的所有工作:

<aop:config>
                <aop:aspect ref="audience">

                        <aop:pointcut id="performance"
                                      expression="execution(* Performer.perform(..))" />

                        <aop:before pointcut-ref="performance" method="takeSeats" />
                        <aop:before pointcut-ref="performance" method="turnOffPhone" />

                        <aop:after-returning pointcut-ref="performance"
                                             method="applaud" />

                        <aop:after-throwing pointcut-ref="performance"
                                            method="demandRefund" />
                </aop:aspect>
        </aop:config>

到此,本篇文章想要介绍的关于面向切面编程的部分讲解完了。下一篇文章我们将对Spring JDBC展开研究

本文Github源代码下载





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值