切面源码
public class LoggingAspect {
public void beforeMethod(JoinPoint joinPoint){
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println(args);
}
public void afterMethod(JoinPoint joinPoint){
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("后置通知"+args);
}
public void afterReturning(JoinPoint joinPoint,Object result){
String name = joinPoint.getSignature().getName();
System.out.println(name+"->"+result);
}
public void afterThrowing(JoinPoint joinPoint, Exception ex){
String name = joinPoint.getSignature().getName();
System.out.println("这是异常通知"+name+"->"+ex);
}
public Object aroundMethod(ProceedingJoinPoint pjd){
String methodname = pjd.getSignature().getName();
Object result = null;
try {
//这里相当于前置通知
System.out.println("前置通知"+"->"+Arrays.asList(pjd.getArgs()));
//执行目标方法
result = pjd.proceed();
//这里相当于返回通知
System.out.println("返回通知"+"->"+result);
} catch (Throwable throwable) {
//这里相当于异常通知
System.out.println("异常通知"+"->"+throwable);
throw new RuntimeException();
}finally {
//这里相当于后置通知
System.out.println("后置通知"+"->"+methodname+"end");
}
return result;
}
}
xml配置
<!--配置bean-->
<bean id="aitihmeticCalculatorImpl" class="AitihmeticCalculatorImpl"></bean>
<!--配置切面的bean-->
<bean id="loggingAspect" class="LoggingAspect"></bean>
<!--配置AOP-->
<aop:config>
<!--配置aop切点表达式-->
<aop:pointcut id="pointcut" expression="execution(* AitihmeticCalculator.*(..))"></aop:pointcut>
<!--配置切面及通知-->
<aop:aspect ref="loggingAspect" order=1>
<!--环绕-->
<aop:around method="aroundMethod" pointcut-ref="pointcut"></aop:around>
<!--前置-->
<aop:before method="beforeMethod" pointcut-ref="pointcut"></aop:before>
<!--后置-->
<aop:after method="afterMethod" pointcut-ref="pointcut"></aop:after>
<!--返回-->
<aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"></aop:after-returning>
<!--异常-->
<aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="ex"></aop:after-throwing>
</aop:aspect>
</aop:config>
</beans>