Spring学习总结之面向切面(AOP)

  1. AOP术语

通知(advice):定义切面是什么以及什么时候使用

连接点(join point):应用在执行过程中能够插入切面的点

切点(pointcut):切点的定义会匹配通知所要织入的一个或多个连接点

切面(aspect):通知和切点的结合

引入(introduction):允许我们向现有的类添加新方法或属性

织入(weaving):把切面应用到目标对象并创建新的代理对象的过程

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

@After:通知方法会在目标方法返回或抛出异常后调用

@AfterReturning:通知方法会在目标方法返回后调用

@AfterThrowing:通知方法会在目标方法抛出异常后调用

@Around:通知方法会将目标方法封装起来

@Before:通知方法会在目标方法调用之前执行

注解使用在切面方法之前,比如:

@Before(“execution(xxx)”)

public void sayHello() {}

此时表示,在xxx方法执行之前,执行切面方法sayHello

  1. pointcut配置如下:

@Pointcut(“execution(* xxxx)”)

public void xxMethod() {}

@Before(“xxMethod()”)

作用:不用每次都写execution,简化了代码,xxMethod只是一个空方法

  1. 使用XML文件配置
<aop:config>

        <aop:aspect ref="aspectClass">

            <aop:pointcut id="p_name" expression="execution(xxx)" />

            <aop:before pointcut-ref="p_name"  method="xxMethod" />

        </aop:aspect>

</aop:config>

         aspectClass表示切面类的bean ID,xxMethod表示用在切面上的方法(通知)

posted @ 2017-04-11 10:12  buaa小松  阅读(285)  评论(0编辑  收藏  举报