增强处理类型
特点
before
前置增强处理,在目标方法前织入增强处理
AfterReturning
后置增强处理,在目标方法正常执行(不出现异常)后织入增强处理
AfterThrowing
异常增强处理,在目标方法抛出异常后织入增强处理
After
最终增强处理,不论方法是否抛出异常,都是会在目标方法最后织入增强处理
Around
环绕增强处理,在目标方法的前后都可以织入增强处理,同时可以控制目标方法的执行及返回值的再加工处理
Around Advice 的第一个参数必须是ProceedingJoinPoint类型,
调用ProceedingJoinPoint类的proceed()方法来控制目标方法是否执行,
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
// start stopwatch
Object retVal = pjp.proceed();
// stop stopwatch
return retVal;
}
xml
<aop:around
pointcut-ref="businessService"
method="doBasicProfiling"/>
...
控制目标方法是否执行
package x.y;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.util.StopWatch;
public class SimpleProfiler {
public Object profile(ProceedingJoinPoint call, String name, int age) throws Throwable {
StopWatch clock = new StopWatch("Profiling for '" + name + "' and '" + age + "'");
try {
clock.start(call.toShortString());
return call.proceed();
} finally {
clock.stop();
System.out.println(clock.prettyPrint());
}
}
}
xml
<!-- this is the object that will be proxied by Spring's AOP infrastructure -->
<bean id="personService" class="x.y.service.DefaultPersonService"/>
<!-- this is the actual advice itself -->
<bean id="profiler" class="x.y.SimpleProfiler"/>
<aop:config>
<aop:aspect ref="profiler"> <aop:pointcut id="theExecutionOfSomePersonServiceMethod"
expression="execution(* x.y.service.PersonService.getPerson(String,int))
and args(name, age)"/>
<aop:around pointcut-ref="theExecutionOfSomePersonServiceMethod"
method="profile"/>
</aop:aspect>
</aop:config>
<aop:aspect id="afterFinallyExample" ref="aBean">
<aop:after
pointcut-ref="dataAccessOperation"
method="doReleaseLock"/>
...
</aop:aspect>
<aop:after-throwing
pointcut-ref="dataAccessOperation"
method="doRecoveryActions"/>
...
还可通过throwing属性指定异常信息的接收对象
<aop:after-throwing
pointcut-ref="dataAccessOperation"
throwing="dataAccessEx"
method="doRecoveryActions"/>
...
参考资料:
手机扫一扫
移动阅读更方便
你可能感兴趣的文章