您的位置:首页 > 编程语言 > Java开发

Spring、XML配置AOP

2016-12-01 00:00 239 查看
新建一个AOP类:

public class MyInterceptor2 {
public void doAccessCheck(){
System.out.println("前置通知 ");
}
public void doAfterReturning(){
System.out.println("后置通知 ");
}
public void doAfter(){
System.out.println("最终通知");
}
public void doAround(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("环绕通知前");
pjp.proceed();
System.out.println("环绕通知后");
}
public void doAfterThrowing(Exception e){
System.out.println("例外通知 例外 e:"+e);
}
}


在beans.xml中注入,并配置AOP:

<aop:aspectj-autoproxy />
<bean id="personIService" class="cn.raffaello.service.impl.PersonServiceImpl"/>
<bean id="myInterceptor2" class="cn.raffaello.aop.MyInterceptor2" />
<aop:config>
<!-- 定义切面 -->
<aop:aspect id="aspect" ref="myInterceptor2">
<!-- 定义切入点 -->
<!-- 拦截所有返回值为String的方法:execution(java.lang.String cn.raffaello.service.impl.PersonServiceImpl.*(..)) -->
<!-- 拦截所有返回值非void的方法:execution(!void cn.raffaello.service.impl.PersonServiceImpl.*(..)) -->
<!-- 拦截第一个参数是String的方法:execution(* cn.raffaello.service.impl.PersonServiceImpl.*(java.lang.String,..)) -->
<!-- 拦截包级子包下的所有类的所有的方法:execution(* cn.raffaello.service.*.*(..)) -->
<!-- 拦截参数为String,并且参数名字为name: execution(* cn.raffaello.service.impl.PersonServiceImpl.*(String)) and args(name) -->
<aop:pointcut id="pointcut" expression="execution(* cn.raffaello.service.impl.PersonServiceImpl.*(java.lang.String))" />
<!-- 前置通知 -->
<aop:before pointcut-ref="pointcut" method="doAccessCheck"/>
<!-- 后置通知 -->
<!-- 拦截返回值为String的方法 <aop:after-returning pointcut-ref="pointcut" method="doAfterReturning" returning="retv"/> -->
<aop:after-returning pointcut-ref="pointcut" method="doAfterReturning" />
<!-- 最终通知 -->
<aop:after pointcut-ref="pointcut" method="doAfter" />
<!-- 环绕通知 -->
<aop:around pointcut-ref="pointcut" method="doAround" />
<!-- 例外通知 -->
<aop:after-throwing pointcut-ref="pointcut" method="doAfterThrowing" throwing="e"/>
</aop:aspect>
</aop:config>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: