时隔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

相关文章

Spring LDAP目录服务的使用示例

《SpringLDAP目录服务的使用示例》本文主要介绍了SpringLDAP目录服务的使用示例... 目录引言一、Spring LDAP基础二、LdapTemplate详解三、LDAP对象映射四、基本LDAP操作4.1 查询操作4.2 添加操作4.3 修改操作4.4 删除操作五、认证与授权六、高级特性与最佳

Spring Shell 命令行实现交互式Shell应用开发

《SpringShell命令行实现交互式Shell应用开发》本文主要介绍了SpringShell命令行实现交互式Shell应用开发,能够帮助开发者快速构建功能丰富的命令行应用程序,具有一定的参考价... 目录引言一、Spring Shell概述二、创建命令类三、命令参数处理四、命令分组与帮助系统五、自定义S

SpringSecurity JWT基于令牌的无状态认证实现

《SpringSecurityJWT基于令牌的无状态认证实现》SpringSecurity中实现基于JWT的无状态认证是一种常见的做法,本文就来介绍一下SpringSecurityJWT基于令牌的无... 目录引言一、JWT基本原理与结构二、Spring Security JWT依赖配置三、JWT令牌生成与

Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码

《Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码》:本文主要介绍Java中日期时间转换的多种方法,包括将Date转换为LocalD... 目录一、Date转LocalDateTime二、Date转LocalDate三、LocalDateTim

如何配置Spring Boot中的Jackson序列化

《如何配置SpringBoot中的Jackson序列化》在开发基于SpringBoot的应用程序时,Jackson是默认的JSON序列化和反序列化工具,本文将详细介绍如何在SpringBoot中配置... 目录配置Spring Boot中的Jackson序列化1. 为什么需要自定义Jackson配置?2.

Java中使用Hutool进行AES加密解密的方法举例

《Java中使用Hutool进行AES加密解密的方法举例》AES是一种对称加密,所谓对称加密就是加密与解密使用的秘钥是一个,下面:本文主要介绍Java中使用Hutool进行AES加密解密的相关资料... 目录前言一、Hutool简介与引入1.1 Hutool简介1.2 引入Hutool二、AES加密解密基础

Linux ls命令操作详解

《Linuxls命令操作详解》通过ls命令,我们可以查看指定目录下的文件和子目录,并结合不同的选项获取详细的文件信息,如权限、大小、修改时间等,:本文主要介绍Linuxls命令详解,需要的朋友可... 目录1. 命令简介2. 命令的基本语法和用法2.1 语法格式2.2 使用示例2.2.1 列出当前目录下的文

Spring Boot项目部署命令java -jar的各种参数及作用详解

《SpringBoot项目部署命令java-jar的各种参数及作用详解》:本文主要介绍SpringBoot项目部署命令java-jar的各种参数及作用的相关资料,包括设置内存大小、垃圾回收... 目录前言一、基础命令结构二、常见的 Java 命令参数1. 设置内存大小2. 配置垃圾回收器3. 配置线程栈大小

SpringBoot实现微信小程序支付功能

《SpringBoot实现微信小程序支付功能》小程序支付功能已成为众多应用的核心需求之一,本文主要介绍了SpringBoot实现微信小程序支付功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作... 目录一、引言二、准备工作(一)微信支付商户平台配置(二)Spring Boot项目搭建(三)配置文件

解决SpringBoot启动报错:Failed to load property source from location 'classpath:/application.yml'

《解决SpringBoot启动报错:Failedtoloadpropertysourcefromlocationclasspath:/application.yml问题》这篇文章主要介绍... 目录在启动SpringBoot项目时报如下错误原因可能是1.yml中语法错误2.yml文件格式是GBK总结在启动S