当前位置: 代码网 > it编程>编程语言>Java > Spring AOP通知类型与实战示例讲解

Spring AOP通知类型与实战示例讲解

2024年11月19日 Java 我要评论
1. @before 前置通知1.1 基本说明在目标方法执行前执行不能阻止目标方法执行(除非抛出异常)可以获取目标方法的参数信息1.2 实现示例@aspect@componentpublic clas

1. @before 前置通知

1.1 基本说明

  • 在目标方法执行前执行
  • 不能阻止目标方法执行(除非抛出异常)
  • 可以获取目标方法的参数信息

1.2 实现示例

@aspect
@component
public class securityaspect {
    @before("@annotation(requiresauth)")
    public void checkauth(joinpoint joinpoint, requiresauth requiresauth) {
        // 获取当前用户信息
        servletrequestattributes attributes = 
            (servletrequestattributes) requestcontextholder.getrequestattributes();
        httpservletrequest request = attributes.getrequest();
        string token = request.getheader("authorization");
        // 验证token
        if (!tokenservice.isvalid(token)) {
            throw new unauthorizedexception("无效的认证令牌");
        }
        // 检查权限
        string requiredrole = requiresauth.role();
        if (!hasrole(token, requiredrole)) {
            throw new forbiddenexception("权限不足");
        }
    }
}

1.3 典型应用场景

  • 权限验证
  • 参数验证
  • 日志记录
  • 事务开始标记
  • 缓存预处理

1.4 获取参数

1.4.1 基本参数获取

@before("execution(* com.example.service.*.*(..))")
public void beforeadvice(joinpoint joinpoint) {
    // 获取方法参数
    object[] args = joinpoint.getargs();
    // 获取方法签名
    methodsignature signature = (methodsignature) joinpoint.getsignature();
    string methodname = signature.getname();
    // 获取参数名称
    string[] parameternames = signature.getparameternames();
    // 获取参数类型
    class<?>[] parametertypes = signature.getparametertypes();
    // 打印参数信息
    for (int i = 0; i < args.length; i++) {
        logger.info("parameter {} ({}) = {}", parameternames[i], parametertypes[i].getsimplename(), args[i]);
    }
}

1.4.2 获取注解参数

@before("@annotation(logparams)")
public void beforewithannotation(joinpoint joinpoint, logparams logparams) {
    // 直接获取注解属性
    string description = logparams.description();
    boolean logresult = logparams.logresult();
    // 获取方法参数
    object[] args = joinpoint.getargs();
    // 根据注解配置记录日志
    if (logparams.includeparameters()) {
        arrays.stream(args)
              .foreach(arg -> logger.info("parameter value: {}", arg));
    }
}

2. @after 后置通知

2.1 基本说明

  • 在目标方法执行后执行(无论是否抛出异常)
  • 不能访问目标方法的返回值
  • 主要用于清理资源或类似的收尾工作

2.2 实现示例

@aspect
@component
public class resourcecleanupaspect {
    @after("execution(* com.example.service.fileservice.*(..))")
    public void cleanup(joinpoint joinpoint) {
        try {
            // 清理临时文件
            string methodname = joinpoint.getsignature().getname();
            logger.info("cleaning up resources after method: {}", methodname);
            cleanuptempfiles();
            // 释放其他资源
            releaseresources();
        } catch (exception e) {
            logger.error("cleanup failed", e);
        }
    }
    private void cleanuptempfiles() {
        // 清理临时文件的具体实现
    }
    private void releaseresources() {
        // 释放资源的具体实现
    }
}

2.3 典型应用场景

  • 资源清理
  • 连接关闭
  • 计数器更新
  • 日志记录
  • 性能监控结束标记

2.4 参数获取

@after("execution(* com.example.service.*.*(..)) && args(id,name,..)")
public void afteradvice(joinpoint joinpoint, long id, string name) {
    // 直接使用参数
    logger.info("method executed with id: {} and name: {}", id, name);
    // 获取目标类信息
    class<?> targetclass = joinpoint.gettarget().getclass();
    // 获取代理类信息
    class<?> proxyclass = joinpoint.getthis().getclass();
}

3. @afterreturning 返回通知

3.1 基本说明

  • 在目标方法成功执行后执行
  • 可以访问目标方法的返回值
  • 可以修改返回值(通过包装类)

3.2 实现示例

@aspect
@component
public class responsehandleraspect {
    @afterreturning(
        pointcut = "execution(* com.example.controller.*.*(..))",
        returning = "result"
    )
    public void handleresponse(joinpoint joinpoint, object result) {
        if (result instanceof list) {
            // 对集合类型结果进行脱敏处理
            list<?> list = (list<?>) result;
            for (object item : list) {
                if (item instanceof userdto) {
                    userdto user = (userdto) item;
                    user.setphone(maskphonenumber(user.getphone()));
                    user.setemail(maskemail(user.getemail()));
                }
            }
        }
    }
    private string maskphonenumber(string phone) {
        // 手机号码脱敏逻辑
        return phone.replaceall("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }
    private string maskemail(string email) {
        // 邮箱脱敏逻辑
        return email.replaceall("(\\w{3})\\w+(@\\w+\\.\\w+)", "$1***$2");
    }
}

3.3 典型应用场景

  • 返回值修改(如数据脱敏)
  • 统计方法成功率
  • 缓存结果
  • 结果格式化
  • 数据集合包装

4. @afterthrowing 异常通知

4.1 基本说明

  • 在目标方法抛出异常时执行
  • 可以访问抛出的异常信息
  • 可以进行异常转换或处理

4.2 实现示例

@aspect
@component
public class exceptionhandleraspect {
    @afterthrowing(
        pointcut = "execution(* com.example.service.*.*(..))",
        throwing = "ex"
    )
    public void handleexception(joinpoint joinpoint, exception ex) {
        string methodname = joinpoint.getsignature().getname();
        string classname = joinpoint.gettarget().getclass().getsimplename();
        // 记录详细错误信息
        logger.error("exception in {}.{}: {}", classname, methodname, ex.getmessage());
        // 发送告警
        if (ex instanceof dataaccessexception) {
            alertservice.senddatabasealert(classname, methodname, ex);
        }
        // 异常分类统计
        metricservice.incrementexceptioncounter(classname, methodname, ex.getclass().getsimplename());
        // 如果需要,可以转换异常类型
        if (ex instanceof sqlexception) {
            throw new databaseexception("数据库操作失败", ex);
        }
    }
}

4.3 典型应用场景

  • 异常记录
  • 异常转换
  • 告警通知
  • 失败重试
  • 错误统计

5. @around 环绕通知

5.1 基本说明

  • 最强大的通知类型,可以完全控制目标方法的执行
  • 可以在方法执行前后添加自定义行为
  • 可以修改方法的参数和返回值
  • 可以决定是否执行目标方法

5.2 实现示例

@aspect
@component
public class cacheaspect {
    @autowired
    private cachemanager cachemanager;
    @around("@annotation(cacheable)")
    public object handlecache(proceedingjoinpoint joinpoint, cacheable cacheable) throws throwable {
        // 构建缓存key
        string key = buildcachekey(joinpoint, cacheable);
        // 尝试从缓存获取
        object cachedvalue = cachemanager.get(key);
        if (cachedvalue != null) {
            logger.debug("cache hit for key: {}", key);
            return cachedvalue;
        }
        // 执行目标方法
        long starttime = system.currenttimemillis();
        object result = null;
        try {
            result = joinpoint.proceed();
            // 记录执行时间
            long executiontime = system.currenttimemillis() - starttime;
            logger.debug("method execution time: {}ms", executiontime);
            // 如果执行时间超过阈值,发送告警
            if (executiontime > 1000) {
                alertservice.sendperformancealert(joinpoint, executiontime);
            }
        } catch (exception e) {
            // 异常处理
            logger.error("method execution failed", e);
            throw e;
        }
        // 将结果放入缓存
        if (result != null) {
            cachemanager.put(key, result, cacheable.ttl());
        }
        return result;
    }
    private string buildcachekey(proceedingjoinpoint joinpoint, cacheable cacheable) {
        // 缓存key构建逻辑
        stringbuilder key = new stringbuilder();
        key.append(joinpoint.getsignature().getdeclaringtypename())
           .append(".")
           .append(joinpoint.getsignature().getname());
        object[] args = joinpoint.getargs();
        if (args != null && args.length > 0) {
            key.append(":");
            for (object arg : args) {
                key.append(arg != null ? arg.tostring() : "null").append(",");
            }
        }
        return key.tostring();
    }
}

5.3 典型应用场景

  • 方法缓存
  • 性能监控
  • 事务处理
  • 重试机制
  • 并发控制
  • 限流处理
@aspect
@component
public class ratelimiteraspect {
    private final ratelimiter ratelimiter = ratelimiter.create(100.0); // 每秒100个请求
    @around("@annotation(ratelimited)")
    public object limitrate(proceedingjoinpoint joinpoint, ratelimited ratelimited) throws throwable {
        if (!ratelimiter.tryacquire(100, timeunit.milliseconds)) {
            throw new toomanyrequestsexception("请求过于频繁,请稍后重试");
        }
        return joinpoint.proceed();
    }
}

6. 最佳实践

  • 选择合适的通知类型
    • 如果只需要前置处理,用@before
    • 如果需要访问返回值,用@afterreturning
    • 如果需要处理异常,用@afterthrowing
    • 如果需要完全控制方法执行,用@around
  • 性能考虑

    • 避免在通知中执行耗时操作
    • 合理使用缓存
    • 注意异常处理的性能影响
  • 代码组织

    • 每个切面专注于单一职责
    • 通知方法保持简洁
    • 复用共同的切入点表达式
  • 异常处理

    • 在通知中要做好异常处理
    • 不要吞掉异常
    • 适当转换异常类型

到此这篇关于spring aop通知类型详解与实战的文章就介绍到这了,更多相关spring aop通知类型内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com