读书人

基于引语方式声明切面(AOP)

发布时间: 2012-08-25 10:06:20 作者: rapoo

基于注解方式声明切面(AOP)
基础知识:


首先启动对@AspectJ注解的支持(蓝色部分):
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<aop:aspectj-autoproxy/>
<bean id="orderservice" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<aop:aspectj-autoproxy/>

//下面是我们交个spring管理的 bean
<bean id="personService" 表示这个函数抛出一个异常 作为doExceptionAction(..)
函数的输入值
@AfterThrowing(pointcut="anyMethod()",throwing="e")
public void doExceptionAction(Exception e) {
System.out.println("e : "+e);
System.out.println("exctution 异常通知");
}





最终通知:

anyMethod():切入点名称
@After("anyMethod()")
public void doReleaseAction() {
System.out.println("exctution 最终通知");
}



环绕通知:

@Around("anyMethod()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("exctution 开始环绕测试");
//必须调用下面的方法
Object object=pjp.proceed();
System.out.println("exctution 结束环绕测试");
return object;
}



总结各个通知执行顺序:

第一种:没有环绕通知

当某个方法被拦截到了先执行->前置通知->执行这个拦截函数->(如果出现例外就执行
例外通知)->最终通知

第二种:
<1、有环绕通知没有异常情况下
当某个方法被拦截到了先执行->前置通知->执行到环绕通知里的方法
Object object=pjp.proceed();前面的代码
调用这个函数pjp.proceed();
然后去执行这个拦截的方法
然后执行后置通知
最终通知
然后执行Object object=pjp.proceed();后面的代码

<2、有环绕通知有异常情况下

当某个方法被拦截到了先执行->前置通知->执行到环绕通知里的方法
Object object=pjp.proceed();前面的代码
调用这个函数pjp.proceed();
然后去执行这个拦截的方法
有异常执行这个异常通知
然后执行最终通知
注意:
Object object=pjp.proceed();后面的代码不会被执行

代码见附件。。。。。。。。。。。。。。。。。。。。

读书人网 >Web前端

热点推荐