AOP简单使用模版
AOP面向切面编程
切面类的定义之模版
package com.xie.service;import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/*** 切面演示 包括切点定义 各通知定义*/
@Aspect
@Component
public class AopService {/*** 定义切点* com.xie.controller.*.*(..) 表示 controller包下 的所有类 的所有方法(*(..))*/@Pointcut("execution(* com.xie.controller.*.*(..))")private void checkMem() {System.out.println("*************** 切点 *****************");}/*** 前置此切点? 切面? 通知 已绑定 切点*/@Before("checkMem()")private void before(JoinPoint joinPoint) {HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();System.out.println("----------------1----------------");System.out.println("前置通知");System.out.println("Url is:" + request.getRequestURL().toString());System.out.println("method is:" + joinPoint.getSignature().getName());System.out.println("----------------1----------------");}/*** 后置此切点? 切面? 通知 已绑定 切点*/@After("checkMem()")private void printMem() {System.out.println("---------------2-----------------");System.out.println("后置通知");System.out.println("After the method, is Mem usage is:" + Runtime.getRuntime().freeMemory() / 1024 / 1024 + "M");System.out.println("----------------2----------------");}/*** 环绕此切点? 切面? 通知 已绑定 切点*/@Around("checkMem()")private Object around(ProceedingJoinPoint joinPoint) throws Throwable {System.out.println("---------------3-----------------");System.out.println("环绕通知");System.out.println("Around for AOP");//获取方法参数值数组Object[] args = joinPoint.getArgs();Object ret = joinPoint.proceed(args);System.out.println("proceed args, result is: " + ret);System.out.println("----------------3----------------");//调用方法return ret;}/*** 后置成功通知 切面? 通知 已绑定 切点*/@AfterReturning(pointcut = "checkMem()", returning = "returnObj")private void afterReturning(Object returnObj) {System.out.println("@AfterReturning 4 ========后置返回(成功)通知===========");System.out.println("--------------------------------");System.out.println("return value is:" + returnObj);System.out.println("--------------------------------");}/*** 后置异常通知 切面? 通知 已绑定 切点*/@AfterThrowing(pointcut = "checkMem()", throwing = "e")private void afterThrowing(JoinPoint joinPoint, Exception e) {System.out.println("@AfterThrowing 5 =====后置异常通知==============");System.out.println("--------------------------------");System.out.println("Exception is:" + e.getMessage());System.out.println("--------------------------------");}
}