spring添加AOP切面-基于XML配置

来源:互联网 发布:智能电视网络设置 编辑:程序博客网 时间:2024/05/02 02:01

写在前面的话:自己试验了一下,如果用xml进行aop配置,则其他的bean也要用xml进行配置(控制器可用注解),否则aop用xml配置,其他bean如果用注解,则无法成功植入切面。

使用xml配置植入aop,关键是三点

1.引入jar包:aopalliance-1.0.jar,aspectjweaver-1.6.8_2.jar

2.实现aop类,很简单,就是一个普普通通的Java类。

public class LogAspect {public void before() {System.out.println("this is log ...");}}

3.配置xml

<!-- 切面,内含自定义切面逻辑 --><bean id="myAspect" class="com.enjoy.aop.LogAspect"></bean><!-- 将定义的切面加入到切入点上 --><aop:config><!-- 切点pointcut可以单独定义实例,然后用pointcut-ref引用,效果一致 --><aop:pointcut expression="execution(* com.enjoy.service.*.*(..))"id="servicePointCut" /><!-- 引用一个自定义的切面实例 --><aop:aspect id="asp1" ref="myAspect"><!-- 在定义的切点之前执行切面中的方法,method属性是指切面中定义的方法,pointcut指需要加入切面逻辑的地方 --><aop:before method="before"pointcut="execution(* com.enjoy.service.*.*(..))" /><!-- 在定义的切点前后均调用切面中的方法 --><!-- <aop:around method="around" pointcut-ref="servicePointCut" /> --><!-- 在定义的切点之后执行切面中的方法 --><!-- <aop:after method="after" pointcut-ref="servicePointCut" /> --><!-- 在定义的切点之后执行切面中的方法,不过该方法存在返回值,需要使用返回值时,如此定义 --><!-- <aop:after-returning method="log" pointcut-ref="servicePointCut" returning="rvt" /> --><!-- 在定义的切点执行后出现了异常,则将异常抛给ex然后放到切面中去处理 --><!-- <aop:after-throwing method="dealException" throwing="ex" pointcut-ref="servicePointCut" /> --></aop:aspect></aop:config><!-- 注:关于befor,after,around三者,是根据其在xml中的顺序来执行的,若将around配置在befor和after之间,则先执行befor, 然后执行around切点方法之前的代码,然后执行around切点之后的代码,然后再执行after。若将around配置在before和after之后,则先执行before, 然后是around的切点方法之前的代码,然后是after,最后是切点方法之后的代码 -->

OK,多讲无意,就是以上三点即可,不需要更改你的其他类,想在哪里植入切面,只需要更改pointcut中的excution表达式即可。另外,在aop类中,未添加after,around等方法,只有类中有这些方法,xml配置后才不会出错。否则会报找不到该方法的异常。


另附,excution表达式的图片,简单可依赖。





0 0
原创粉丝点击