AspectJ:java社区里最完整最流行的AOP框架
在Spring2.0以上版本,可以使用基于AspectJ注解或基于XML配置的AOP
<!--使AspectJ注解起作用,自动为匹配的类生成代理对象-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
把横切关注点的代码抽象到切面的类中
@Before("execution(public int com.atguigu.spring.aopimpl.ArithmeticCalculator.*(..))")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("The method:"+methodName+" begin with:"+args);
}
@After("execution(public int com.atguigu.spring.aopimpl.ArithmeticCalculator.*(..))")
public void afterMethod(JoinPoint joinPoint){
String method = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("The method:"+method+" end with"+args);
}
@AfterReturning(value = "execution(public int com.atguigu.spring.aopimpl.ArithmeticCalculator.*(..))",
returning = "result")
public void aftetReturning(JoinPoint joinPoint,Object result){
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("The method:"+methodName+" end with"+result);
}
@Around("execution(public int com.atguigu.spring.aopimpl.ArithmeticCalculator.*(..))")
public Object around(ProceedingJoinPoint pjp){
Object result = null;
String methodName = pjp.getSignature().getName();
List<Object> args = Arrays.asList(pjp.getArgs());
try {
//前置通知
System.out.println("The method:"+methodName+" begin with:"+args);
result = pjp.proceed();
//返回通知
System.out.println("The method:"+methodName+" end with:"+result);
} catch (Throwable throwable) {
//异常通知
System.out.println("The method:"+methodName+" occurs with:"+throwable);
}
//后置通知
System.out.println("The method "+methodName+" ends");
return result;
}
@Order(level)指定切面的优先级,值越小优先级越高
//切点表达式
@Pointcut("execution(public int com.atguigu.spring.aopimpl.ArithmeticCalculator.*(..))")
public void declareJoinPoint(){}
//引用方式
@Before("declareJoinPoint()")
public void beforeMethod(JoinPoint joinPoint){
<aop:config>
<!--配置切点表达式-->
<aop:pointcut id="pointcut" expression="execution(* com.atguigu.spring.aopxml.ArithmeticCalculator.*(..))"/>
<!--配置切面-->
<aop:aspect ref="loggingAspect" order="2">
<!--配置通知-->
<aop:before method="beforeMethod" pointcut-ref="pointcut"></aop:before>
<aop:after method="afterMethod" pointcut-ref="pointcut"></aop:after>
<aop:after-returning method="aftetReturning" pointcut-ref="pointcut" returning="result"></aop:after-returning>
<aop:after-throwing method="aftetThrowing" pointcut-ref="pointcut" throwing="ex"></aop:after-throwing>
</aop:aspect>
</aop:config>
原文:https://www.cnblogs.com/ylcc-zyq/p/12547919.html