Spring3之基于Aspect实现AOP

简介

使用 Aspect 搭配 Spring 可轻松实现 AOP;本章将通过一个完整示例演示如何实现这一功能

实现步骤

  1. 修改 beans.xml 配置文件的 schema 部分;可以在 spring-framework-reference.html 文件通过搜索关键字 “/aop” 找到配置 schema,然后把这三句 schema 添加到 beans.xml 文件中
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
     xmlns:aop="http://www.springframework.org/schema/aop"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
      <!-- 设置Spring去哪些包中找annotation -->
   <context:component-scan base-package="com.ibm.oneteam"/>
</beans>
  1. 在 beans.xml 文件中添加如下基本配置
<context:component-scan base-package="com.duzimei.blog"/> <!-- 设置要被扫描的基础包 -->
<aop:aspectj-autoproxy/> <!-- 打开基于 Annotation 的AOP 设置 -->
  1. 添加如下 3 个依赖包到项目
    在这里插入图片描述

  2. 新建一个类 LogAspect.class, 添加如下代码


 // 声明这是一个切面类
public class LogAspect {
    // 在函数调用前执行
    ("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());
    }
    
    // 在函数调用过程中执行
    ("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;
    }
    
    // 在函数调用后执行
    ("execution(* com.duzimei.blog.*.add(..)) || "
        + "execution(* com.duzimei.blog.*.controller.delete(..))")
    public void logAfter() {
        System.out.println(“完成添加日志”);
    }
    
    // 函数调用出现异常
    (throwing="e", pointcut="execution(* com.duzimei.blog.*.add(..)) || "
        + "execution(* com.duzimei.blog.controller.*.delete(..))")
    public void logError(Throwable e) {
        System.out.println("添加日志失败, " + e.getMessage());
    }

    // 函数调用完毕后处理返回值
    (pointcut="execution(* com.duzimei.blog.*.add(..)) || "
        + "execution(* com.duzimei.blog.controller.*.delete(..))")
    public Object afterReturn() {
        System.out.println("获取到函数返回值");
        return result;
    }
}
  1. 测试一下;注意查看如下打印结果的执行顺序
    在这里插入图片描述

重要属性讲解

(1) @Before:在函数调用前执行

(2) @Around:在函数调用过程中执行,添加了该注解的方法是最主要的方法,基本上所有的逻辑都应在这个这个方法里

(3) @After:在函数执行完毕后执行

(4) @AfterThrowing:函数执行过程中出现异常;不常用,一般在 @Around 注解的方法中用 try … catch 处理较好

(5) @AfterReturning:函数执行完毕后执行,可获取、操作函数的返回值

(6) @Pointcut:用于定义切面,方便其他注解配置;如上面的例子中,每个方法的注解上都写了 execution 表达式,在实际开发过程中,可通过@Poingcut 定义不同的切面,然后在注解中直接调用,可简化代码;例如:

public class Pointcuts {
    // 定义只处理 dao 层 add 方法的切面配置
    ("execution(* com.duzimei.blog.dao.*.add(..))")
    public void logAdd() { }
    
    // 定义值处理 controller 层 delete 方法的切面配置
    ("execution(* com.duzimei.blog.controller.*.delete(..))")
    public void logDelete() { }
}

然后在 LogAspect.class 中可以这样使用



public class LogAspect {   
    ("com.duzimei.blog.aop.Pointcuts.logAdd()") 
    public void logBefore() {
        ... ...
    }
}

(7) execution 表达式:execution(* com.duzimei.blog.*.add(…)) 这个表达式中,第一个 * 表示任意返回值,第二个 * 表示 com.duzimei.blog 包路径下的所有类,第三个 * 表示以 add 开头的所有方法,(…) 表示方法的任意参数;多个表达式通过 || 分隔开

在 XML 文件中配置

上面演示的是通过直接在类中添加注解的方式实现 AOP,如果要使用 XML 的方式配置,只需添加如下代码即可

<bean id="logAspect" class="com.duzimei.blog.aop.LogAspect"/> <!-- 注入日志工具类 -->
<aop:config>
    <!-- 定义切面 -->
    <aop:aspect id="logAspect" ref="logAspect">
        <!-- 定义表达式和步骤 -->
        <aop:pointcut id="logPointcut" expression="execution(* com.duzimei.blog.dao.*.add(..))"/>
        <aop:before method="logStart" point-ref="logPointcut"/>
        <aop:after method="logAfter" point-ref="logPointcut"/>
    </aop:aspect>
</aop:config>

补充
在实际开发过程中,经常需要通过 AOP 实现日志记录功能,这里面稍微麻烦的地方在于如何获取方法的参数以及对应的值,因为我们在拦截的时候是不知道方法参数的类型的;这里有个简单的实现方式,参考代码如下

("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 记录参数
	Map<String, 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();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值