时隔1年,我终于弄懂了Java 中的 AOP操作

2024-05-28 03:12

本文主要是介绍时隔1年,我终于弄懂了Java 中的 AOP操作,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1. AOP概述

2. AOP快速入门 

依赖:

        <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId><version>${spring-boot.version}</version></dependency>

 示例:记录方法的执行耗时

创建一个aop类:(在执行com.etc.aoptest.service.impl.UserServiceImpl类下否方法时就会进行环绕通知)

package com.etc.aoptest.aop;import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;@Slf4j
@Component
@Aspect
public class TimeAspect {@Around("execution(* com.etc.aoptest.service.impl.UserServiceImpl.*(..))")public Object recordTime(ProceedingJoinPoint joinPoint) throws Throwable{long begin = System.currentTimeMillis();Object result = joinPoint.proceed();long end = System.currentTimeMillis();log.info(joinPoint.getSignature() + "方法执行耗时: {}ms",end - begin);return result;}}

3. AOP的核心概念

4. AOP通知类型

创建一个aop类用于测试AOP通知类型

package com.etc.aoptest.aop;import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;@Slf4j
@Component
@Aspect
public class AspectType {//环绕通知,目标方法前后都被执行@Around("execution(* com.etc.aoptest.service.impl.UserServiceImpl.*(..)) ")public void around(ProceedingJoinPoint joinPoint) throws Throwable {log.info("方法执行前..................................");Object result = joinPoint.proceed();log.info("方法执行后..................................");}//环绕前通知@Before("execution(* com.etc.aoptest.service.impl.UserServiceImpl.*(..)) ")public void before() {log.info("before通知..................................");}//环绕后通知@After("execution(* com.etc.aoptest.service.impl.UserServiceImpl.*(..)) ")public void after() {log.info("after通知..................................");}//返回后通知@AfterReturning("execution(* com.etc.aoptest.service.impl.UserServiceImpl.*(..)) ")public void afterReturning() {log.info("afterReturning通知..................................");}//异常后通知@AfterThrowing("execution(* com.etc.aoptest.service.impl.UserServiceImpl.*(..)) ")public void afterThrowing(){log.info("afterThrowing通知..................................");}}

可以通过@Pointcut简化冗余切面点表达式

修改后如下所示:

package com.etc.aoptest.aop;import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;@Slf4j
@Component
@Aspect
public class AspectType {@Pointcut("execution(* com.etc.aoptest.service.impl.UserServiceImpl.*(..)) ")private void pt(){};//环绕通知,目标方法前后都被执行//@Around("execution(* com.etc.aoptest.service.impl.UserServiceImpl.*(..)) ")@Around("pt()")public void around(ProceedingJoinPoint joinPoint) throws Throwable {log.info("方法执行前..................................");Object result = joinPoint.proceed();log.info("方法执行后..................................");}//环绕前通知//@Before("execution(* com.etc.aoptest.service.impl.UserServiceImpl.*(..)) ")@Before("pt()")public void before() {log.info("before通知..................................");}//环绕后通知//@After("execution(* com.etc.aoptest.service.impl.UserServiceImpl.*(..)) ")@After("pt()")public void after() {log.info("after通知..................................");}//返回后通知//@AfterReturning("execution(* com.etc.aoptest.service.impl.UserServiceImpl.*(..)) ")@AfterReturning("pt()")public void afterReturning() {log.info("afterReturning通知..................................");}//异常后通知//@AfterThrowing("execution(* com.etc.aoptest.service.impl.UserServiceImpl.*(..)) ")@AfterThrowing("pt()")public void afterThrowing(){log.info("afterThrowing通知..................................");}}

其他aop类也可以引入当前aop类的切面点表达式

不过需要将private void pt()修改为public void pt();

示例:

package com.etc.aoptest.aop;import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;@Slf4j
@Component
@Aspect
public class TimeAspect {//@Around("execution(* com.etc.aoptest.service.impl.UserServiceImpl.*(..))")@Around("com.etc.aoptest.aop.AspectType.pt()")public Object recordTime(ProceedingJoinPoint joinPoint) throws Throwable{long begin = System.currentTimeMillis();Object result = joinPoint.proceed();long end = System.currentTimeMillis();log.info(joinPoint.getSignature() + "方法执行耗时: {}ms",end - begin);return result;}}

5. AOP执行顺序

6. AOP切入点表达式

7.  AOP多个切入点表达式 @Annotation

 

这样就无需写表达式,只需要写在对应的方法上加上自定义的注解,这时Annotation就会通过对应的注解切入点表达式。 

示例:

步骤一

首先在一个log包内创建UserLog自定义注解

UserLog:

package com.etc.aoptest.log;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME) //运行时生效
@Target(ElementType.METHOD) //标识方法
public @interface UserLog {}

步骤二

aop包下创建AnnoAspect 用于AOP注入时实现的环绕通知

package com.etc.aoptest.aop;import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;@Slf4j
@Component
@Aspect
public class AnnoAspect {@Pointcut("@annotation(com.etc.aoptest.log.UserLog)")private void pt(){}@Around("pt()")public Object around(ProceedingJoinPoint joinPoint) throws Throwable {log.info("UserLog-方法执行前..................................");Object result = joinPoint.proceed();log.info("UserLog-方法执行后..................................");return result;}}

步骤三 

在所注入AOP的方法上加上自定义注解名@UserLog

package com.etc.aoptest.controller;import com.etc.aoptest.log.UserLog;
import com.etc.aoptest.pojo.User;
import com.etc.aoptest.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {private final IUserService userService;@UserLog@RequestMapping("/getList")public List<User> getList(){return userService.getList();}@UserLog@RequestMapping("/{id}")public User getById(@PathVariable Long id){return userService.getById(id);}}

8. AOP连接点

通过JoinPoint来获取方法执行时的相关信息,只有环绕通知使用ProceedingJoinPoint来获取相关信息而另外四种AOP通知类型则通过JoinPoint来获取相关信息。

 9. AOP实战演练(操作日志表)

要求:实现操作日志表,记录对数据库的增删改查操作的日志。

步骤一

先创建一个记录日志表实体并创建该数据库

pojo.OperateLog:
package com.etc.aoptest.pojo;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;import java.time.LocalDateTime;@Data
@TableName("tb_operate_log")
public class OperateLog {@TableId(type = IdType.AUTO)private Long id;//操作者ID@TableField("operate_Id")private Long operateId;//类名@TableField("class_name")private String className;//方法名@TableField("method_name")private String methodName;//方法参数@TableField("method_params")private String methodParams;//返回结果@TableField("return_value")private String returnValue;//操作耗时@TableField("cost_time")private Long costTime;//操作时间@TableField("operate_time")private LocalDateTime operateTime;
}

anno.Log:

package com.etc.aoptest.log;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Log {
}

 步骤二

编写AOP操作,用于在执行该方法时进行环绕通知操作,使用ProceedingJoinPoint获取执行方法的相关信息存入OperateLog数据库中

package com.etc.aoptest.aop;import com.alibaba.fastjson.JSONObject;
import com.etc.aoptest.mapper.OperateLogMapper;
import com.etc.aoptest.pojo.OperateLog;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;import java.time.LocalDateTime;
import java.util.Arrays;@Component
@Aspect
@RequiredArgsConstructor
@Slf4j
public class LogAspect {private final OperateLogMapper operateLogMapper;@Around("@annotation(com.etc.aoptest.log.Log)")public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable{//TODO 1.通过HttpServletRequest获取token值通过JWT解析获取当前用户id 或者 2.通过ThreadLocal获取当前用户idLong operateId = 1L;//类名String className = joinPoint.getTarget().getClass().getName();//方法名String methodName = joinPoint.getSignature().getName();Object[] args = joinPoint.getArgs();//方法参数String methodParams = Arrays.toString(args);Long begin = System.currentTimeMillis();Object result = joinPoint.proceed();Long end = System.currentTimeMillis();//方法返回值String returnValue = JSONObject.toJSONString(result);//操作耗时Long costTime = end - begin;OperateLog operateLog = new OperateLog(null,operateId,className,methodName,methodParams,returnValue,costTime,LocalDateTime.now());operateLogMapper.insert(operateLog);log.info("AOP记录日志操作:{}",operateLog);return result;}
}

步骤三

 对于要进行AOP切入的方法前加上自定义的@Log注解

package com.etc.aoptest.controller;import com.etc.aoptest.log.Log;
import com.etc.aoptest.pojo.User;
import com.etc.aoptest.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {private final IUserService userService;@Log@RequestMapping("/getList")public List<User> getList(){return userService.getList();}@Log@RequestMapping("/{id}")public User getById(@PathVariable Long id){return userService.getById(id);}}

这篇关于时隔1年,我终于弄懂了Java 中的 AOP操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1009384

相关文章

javax.net.ssl.SSLHandshakeException:异常原因及解决方案

《javax.net.ssl.SSLHandshakeException:异常原因及解决方案》javax.net.ssl.SSLHandshakeException是一个SSL握手异常,通常在建立SS... 目录报错原因在程序中绕过服务器的安全验证注意点最后多说一句报错原因一般出现这种问题是因为目标服务器

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

spring中的ImportSelector接口示例详解

《spring中的ImportSelector接口示例详解》Spring的ImportSelector接口用于动态选择配置类,实现条件化和模块化配置,关键方法selectImports根据注解信息返回... 目录一、核心作用二、关键方法三、扩展功能四、使用示例五、工作原理六、应用场景七、自定义实现Impor

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

Java对异常的认识与异常的处理小结

《Java对异常的认识与异常的处理小结》Java程序在运行时可能出现的错误或非正常情况称为异常,下面给大家介绍Java对异常的认识与异常的处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参... 目录一、认识异常与异常类型。二、异常的处理三、总结 一、认识异常与异常类型。(1)简单定义-什么是

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.