网站开发邮件,游戏网站模板免费下载,仿站模板,wordpress来建站简介
使用 Aspect 搭配 Spring 可轻松实现 AOP#xff1b;本章将通过一个完整示例演示如何实现这一功能
实现步骤
修改 beans.xml 配置文件的 schema 部分#xff1b;可以在 spring-framework-reference.html 文件通过搜索关键字 “/aop” 找到配置 schema#xff0c;然后…简介
使用 Aspect 搭配 Spring 可轻松实现 AOP本章将通过一个完整示例演示如何实现这一功能
实现步骤
修改 beans.xml 配置文件的 schema 部分可以在 spring-framework-reference.html 文件通过搜索关键字 “/aop” 找到配置 schema然后把这三句 schema 添加到 beans.xml 文件中
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/contextxmlns:aophttp://www.springframework.org/schema/aopxsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd!-- 设置Spring去哪些包中找annotation --context:component-scan base-packagecom.ibm.oneteam/
/beans在 beans.xml 文件中添加如下基本配置
context:component-scan base-packagecom.duzimei.blog/ !-- 设置要被扫描的基础包 --
aop:aspectj-autoproxy/ !-- 打开基于 Annotation 的AOP 设置 --添加如下 3 个依赖包到项目 新建一个类 LogAspect.class, 添加如下代码
Component
Aspect // 声明这是一个切面类
public class LogAspect {// 在函数调用前执行Before(execution(* com.duzimei.blog.dao.*.add(..) || execution(* com.duzimei.blog.controller.*.delete(..)))public void logBefore(JoinPoint jp) {System.out.println(开始添加日志);// 输出执行对象System.out.println(jp.getTarget());// 输出执行方法System.out.println(jp.getSignature().getName());}// 在函数调用过程中执行Around(execution(* com.duzimei.blog.dao.*.add(..)) || execution(* com.duzimei.blog.controller.*.delete(..)))public Object logAround(ProceedingJoinPoint pjp) throws Throwable {System.out.print(1.开始添加日志);Object result pjp.proceed();System.out.println(2.完成添加日志);return result;}// 在函数调用后执行After(execution(* com.duzimei.blog.*.add(..)) || execution(* com.duzimei.blog.*.controller.delete(..)))public void logAfter() {System.out.println(“完成添加日志”);}// 函数调用出现异常AfterThrowing(throwinge, pointcutexecution(* com.duzimei.blog.*.add(..)) || execution(* com.duzimei.blog.controller.*.delete(..)))public void logError(Throwable e) {System.out.println(添加日志失败, e.getMessage());}// 函数调用完毕后处理返回值AfterReturning(pointcutexecution(* com.duzimei.blog.*.add(..)) || execution(* com.duzimei.blog.controller.*.delete(..)))public Object afterReturn() {System.out.println(获取到函数返回值);return result;}
}测试一下注意查看如下打印结果的执行顺序
重要属性讲解
(1) Before在函数调用前执行
(2) Around在函数调用过程中执行添加了该注解的方法是最主要的方法基本上所有的逻辑都应在这个这个方法里
(3) After在函数执行完毕后执行
(4) AfterThrowing函数执行过程中出现异常不常用一般在 Around 注解的方法中用 try … catch 处理较好
(5) AfterReturning函数执行完毕后执行可获取、操作函数的返回值
(6) Pointcut用于定义切面方便其他注解配置如上面的例子中每个方法的注解上都写了 execution 表达式在实际开发过程中可通过Poingcut 定义不同的切面然后在注解中直接调用可简化代码例如
public class Pointcuts {// 定义只处理 dao 层 add 方法的切面配置Pointcut(execution(* com.duzimei.blog.dao.*.add(..)))public void logAdd() { }// 定义值处理 controller 层 delete 方法的切面配置Pointcut(execution(* com.duzimei.blog.controller.*.delete(..)))public void logDelete() { }
}然后在 LogAspect.class 中可以这样使用
Component
Aspect
public class LogAspect { Before(com.duzimei.blog.aop.Pointcuts.logAdd()) public void logBefore() {... ...}
}(7) execution 表达式execution(* com.duzimei.blog.*.add(…)) 这个表达式中第一个 * 表示任意返回值第二个 * 表示 com.duzimei.blog 包路径下的所有类第三个 * 表示以 add 开头的所有方法(…) 表示方法的任意参数多个表达式通过 || 分隔开
在 XML 文件中配置
上面演示的是通过直接在类中添加注解的方式实现 AOP如果要使用 XML 的方式配置只需添加如下代码即可
bean idlogAspect classcom.duzimei.blog.aop.LogAspect/ !-- 注入日志工具类 --
aop:config!-- 定义切面 --aop:aspect idlogAspect reflogAspect!-- 定义表达式和步骤 --aop:pointcut idlogPointcut expressionexecution(* com.duzimei.blog.dao.*.add(..))/aop:before methodlogStart point-reflogPointcut/aop:after methodlogAfter point-reflogPointcut//aop:aspect
/aop:config补充 在实际开发过程中经常需要通过 AOP 实现日志记录功能这里面稍微麻烦的地方在于如何获取方法的参数以及对应的值因为我们在拦截的时候是不知道方法参数的类型的这里有个简单的实现方式参考代码如下
Around(execution(* com.dufu.blog.controller.*.*(..)))
public Object around(ProceedingJoinPoint point) throws Throwable {// 获取方法参数Object[] args point.getArgs();// 获取方法签名MethodSignature signature (MethodSignature)point.getSignature();// 获取执行对象Object target point.getTarget();// 获取方法Method method target.getClass().getMethod(signature.getName(), signature.getParameterTypes());// 如果方法上添加了 Logger 注解, 记录用户操作if(method.isAnnotationPresent(Logger.class)) {LocalVariableTableParameterNameDiscoverer parameter new LocalVariableTableParameterNameDiscoverer();// 获取方法参数名称String[] paramNames parameter.getParameterNames(method);// 通过 Map 记录参数MapString, Object paramMap new HashMap();if(null ! paramNames paramNames.length 0) {for(Integer i 0; i paramNames.length; i) {// 忽略类型是 request, response, multipartFile 的参数if(args[i] instanceof HttpServletRequest || args[i] instanceof HttpServletResponse || args[i] instanceof MultipartFile) {continue;}paramMap.put(paramNames[i], args[i]);}}// 打印一下参数信息System.out.println(JSON.toJSONString(paramMap));}return point.proceed();
}