简介
AOP意为“面向切面编程”,这样的名字并不是非常容易理解,且容易产生一些误导。AOP是新一代软件开发方式”,在Spring中提供了面向切面编程的丰富支持,允许通过分离应用的业务逻辑与系统级服务(例如审计(auditing)和事务(transaction)管理)进行内聚性的开发。应用对象只实现它们应该做的——完成业务逻辑——仅此而已。它们并不负责(甚至是意识)其它的系统级关注点,例如日志或事务支持。
AOP主要功能有 日志记录,性能统计,安全控制,事务处理,异常处理。
OK,教程走起。。。。(看完保证你不再手动打印出入参了啥)
PS:本教程是基于spring boot项目讲解的
1、第一步肯定是新建项目,引入依赖啦
pom文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.8</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>springboot-logback-async</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-logback-async</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- 构建成可运行的Web项目 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- AOP 依赖必须加进来-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<!-- 打印日志需要 -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、新建两个实体类 UserDto、Result,代码如下:
import lombok.Data;
/**
* body入参
*/
@Data
public class UserDto {
private String userId;
private String userName;
}
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* 返回对象
* @param <T>
*/
@Data
@AllArgsConstructor
public class Result<T> {
private static final int success = 0;
private static final int fail = -1;
private static final String successMsg = "请求成功";
private static final String failMsg = "请求失败";
private int code;
private String message;
private T data;
public static <T> Result<T> returnSuccess(T data) {
return new Result<T>(success, successMsg, data);
}
public static <T> Result<T> returnFail(T data) {
return new Result<T>(fail, failMsg, null);
}
}
3、新建一个测试接口类InitRest
import com.example.demo.dto.UserDto;
import com.example.demo.model.Result;
import org.springframework.web.bind.annotation.*;
//使用restful风格
@RestController
public class InitRest {
//测试get入参
@GetMapping("/hello")
public Result<String> hello(@RequestParam String userId) {
return Result.returnSuccess("Hello get...");
}
//测试body入参
@PostMapping("/hello")
public Result<UserDto> hello(@RequestBody UserDto userDto) {
userDto.setUserId("你的名字被修改啦。。。");
return Result.returnSuccess(userDto);
}
}
4、关键的一步,新建一个AOP类:WebLog.java
import com.google.gson.Gson;
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.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
@Slf4j
//下面两个注解是必须的,少一个都不行哦
@Aspect
@Configuration
public class WebLog {
//标记切入点,为指定包下的所有类的所有public方法
@Pointcut(value = "execution(public * com.example.demo.rest.*.* (*))")
public void webLog() {
}
@Around(value = "webLog()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String requestId = UUID.randomUUID().toString().replace("-", "");
//打印入参
log.info("requestId={},请求入参 {}", requestId, new Gson().toJson(joinPoint.getArgs()));
Object object = joinPoint.proceed();
//打印出参
log.info("requestId={},请求出参 {}", requestId, new Gson().toJson(object));
return object;
}
}
5、OK,整完了,看一下目前的目录结构:
目录结构6、启动项目,访问接口,注意看日志打印哦
启动成功get请求
get请求日志
post请求
post请求日志
OK,完美实现,出入参日志打印,此法简单又方便,你领会了嘛???
关于此教程用到的几个注解,有不太清楚的朋友可留言询问哦!
网友评论