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

相关文章

python panda库从基础到高级操作分析

《pythonpanda库从基础到高级操作分析》本文介绍了Pandas库的核心功能,包括处理结构化数据的Series和DataFrame数据结构,数据读取、清洗、分组聚合、合并、时间序列分析及大数据... 目录1. Pandas 概述2. 基本操作:数据读取与查看3. 索引操作:精准定位数据4. Group

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav

深入浅出SpringBoot WebSocket构建实时应用全面指南

《深入浅出SpringBootWebSocket构建实时应用全面指南》WebSocket是一种在单个TCP连接上进行全双工通信的协议,这篇文章主要为大家详细介绍了SpringBoot如何集成WebS... 目录前言为什么需要 WebSocketWebSocket 是什么Spring Boot 如何简化 We