AspectJ的好处是可以将所有的通知写到一个类中,二schema-based需要不同的类实现不同的接口
例如
public class MyAdvice {
public void beforeMethod() {
System.out.println("before");
}
public void afterMethod() {
System.out.println("after");
}
public void after_returning_Method() {
System.out.println("after_returning");
}
public void throwMethod() {
System.out.println("throw");
}
public Object aroundMethod(ProceedingJoinPoint pj) throws Throwable{
System.out.println("around before");
Object result = pj.proceed();
System.out.println("around after");
return result;
}
}
配置xml
<bean id="demo" class="com.lee.service.DemoService"/>
<bean id="myadvice" class="com.lee.advice.MyAdvice"/>
<aop:config>
<aop:pointcut expression="execution(* com.lee.service.*.*(..))" id="mypoint"/>
<aop:aspect ref="myadvice">
<aop:before method="beforeMethod" pointcut-ref="mypoint"/>
<aop:after-returning method="after_returning_Method" pointcut-ref="mypoint"/>
<aop:after method="afterMethod" pointcut-ref="mypoint"/>
<aop:around method="aroundMethod" pointcut-ref="mypoint"/>
<aop:after-throwing method="throwMethod" pointcut-ref="mypoint"/>
</aop:aspect>
</aop:config>
切点类
public class DemoService {
public void demoMethod() {
//int i = 5/0;
System.out.println("DemoMethod execute");
}
}
当切点没有错误时,结果如下
before
around before
DemoMethod execute
around after
after
after_returning
当有错误时
before
around before
throw
after
Exception in thread "main" java.lang.ArithmeticException: / by zero
可见当有没有错误,<aop:after/>标签始终执行