开启注解扫描
<context:component-scan base-package="aopSpring"></context:component-scan>
将AOP的注解应用到容器中 <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
把横切关注点的代码添加到切面类中
@component
@Aspect
应用如下
aop/ArithMath
import org.springframework.stereotype.Component; @Component public class ArithMath { public ArithMath(){} public int add(int i,int j){ return i + j; } public int div(int i,int j){ return i / j; } }在ArithMath方法执行过程中插入日志
编写切面类aop/ArithMathAopImp
@Component @Aspect public class ArithMathAopImp { //前置增强@Before @Before("execution(* aopSpring.ArithMath.add(int,int))") public void loggingArithMath(JoinPoint joinPoint){ //添加参数JoinPoint 可以获取目标的参数 String methd = joinPoint.getSignature().getName(); List<Object> list = Arrays.asList(joinPoint.getArgs()); System.out.println("the mathod "+ methd +" on load begin whih "+list); }//后置增强不可访问方法返回值 @After(value="execution(* aopSpring.ArithMath.add(int,int))") public void AfterMethod(JoinPoint joinPoint){ String method = joinPoint.getSignature().getName(); System.out.println("the mathod "+ method +" on end!"); }
//返回通知 @AfterReturning(value="execution(* aopSpring.ArithMath.add(int,int))",returning="rt") public void AfterReturn(JoinPoint joinPoint,Object rt){ String method = joinPoint.getSignature().getName(); System.out.println("the mathod "+ method +" return "+rt); }
//异常通知, @AfterThrowing(value="execution(* aopSpring.ArithMath.*(int,int))",throwing="ex") public void AfterThrowingMethod(JoinPoint joinPoint,Exception ex){ //指定特定的异常(Exception )发生时才执行代码 String method = joinPoint.getSignature().getName(); System.out.println("the mathod "+ method +" throw "+ex); }
/** * 环绕通知@Around * 通知必须加参数ProceedingJoinPoint,且必须有返回值 * proceed()表示执行目标方法 */ @Around("execution(* aopSpring.ArithMath.*(int,int))") public Object AroundMethed(ProceedingJoinPoint pj){ Object rt = null; String method = pj.getSignature().getName(); try { //前置 System.out.println(method + "before"); rt = pj.proceed(); //后置 System.out.println(method + "after"); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(method + e); } //后置 System.out.println(method + "returnning"); return rt; }
转载于:https://www.cnblogs.com/zengjp/p/7171194.html
相关资源:基于注解实现SpringAop