search
HomeJavajavaTutorialHow SpringBoot uses AOP to record interface operation logs

1. Introduction to AOP

1. What is AOP

AOP: Aspect Oriented Programming

AOP focuses not on A certain class or certain methods; control a large number of resources and focus on a large number of classes and methods.

2.AOP application scenarios and common terms

  • Permission control, cache control, transaction control, distributed tracing, exception handling Wait

  • Target: target class, that is, the class that needs to be proxied. For example: UserService

  • Joinpoint: The so-called connection point refers to those methods that may be intercepted. For example: All methods

  • PointCut Pointcut: A connection point that has been enhanced. For example: addUser()

  • Advice notification/enhancement, enhance the code. For example: after, before

  • Weaving (weaving): refers to the process of applying enhanced advice to the target object target to create a new proxy object proxy.

  • Aspect: It is the combination of pointcut and notification advice

3. Characteristics of AOP

1) Reduce the coupling between modules and improve the aggregation of business code. (High cohesion and low coupling)

2) Improved code reusability

3) Improved system scalability. (Higher versions are compatible with lower versions)

4) New functions can be added without affecting the original functions

2. SpringBoot uses AOP to implement the process

1.Introduce dependencies

<!-- Spring AOP -->
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2.Encapsulate the logging entity class

@Getter
@Setter
@ApiModel(value = "Systemlog对象", description = "")
public class Systemlog implements Serializable {

    private static final long serialVersionUID = 1L;

      @ApiModelProperty("ID")
      @TableId(value = "id", type = IdType.AUTO)
      private Integer id;

      @ApiModelProperty("用户名")
      private String userName;

      @ApiModelProperty("用户ID")
      private Integer userId;

      @ApiModelProperty("操作描述")
      private String operate;

      @ApiModelProperty("模块")
      private String module;

      @ApiModelProperty("创建日志时间")
      @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
      private Date createTime;

      @ApiModelProperty("操作结果")
      private String result;

}

3.Write annotation classes(custom log Annotation class)

/**
 * controller层切面日志注解
 * @author hsq
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SystemControllerLog {
    // 操作描述
    String operate();
    // 模块
    String module();
}

4. Write the aspect class of the operation log

**
 * @author hsq
 */
@Aspect
@Component
public class SystemLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);

    @Autowired
    private ISystemlogService iSystemlogService;

    @Autowired
    private UserService userService;

    /**
     * Controller层切点
     */
    @Pointcut("@annotation(com.hsq.demo.config.SystemControllerLog)")
    public void SystemControllerLog(){

    }
    
   
    /**
     * 前置通知 用于拦截Controller层记录用户的操作的开始时间
     * @param joinPoint 切点
     * @throws InterruptedException
     */
    @Before("SystemControllerLog()")
    public void doBefore(JoinPoint joinPoint) throws InterruptedException{
        logger.info("进入日志切面前置通知!");

    }

    @After("SystemControllerLog()")
    public void doAfter(JoinPoint joinPoint) {
        logger.info("进入日志切面后置通知!");

    }

    /**value切入点位置
     * returning 自定义的变量,标识目标方法的返回值,自定义变量名必须和通知方法的形参一样
     * 特点:在目标方法之后执行的,能够获取到目标方法的返回值,可以根据这个返回值做不同的处理
     */
    @AfterReturning(value = "SystemControllerLog()", returning = "ret")
    public void doAfterReturning(Object ret) throws Throwable {
    }

    /***
     * 异常通知 记录操作报错日志
     * * @param joinPoint
     * * @param e
     * */
    @AfterThrowing(pointcut = "SystemControllerLog()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
        logger.info("进入日志切面异常通知!!");
        logger.info("异常信息:" + e.getMessage());
    }
        
        
    //使用这个方法先注释前面三个方法,留before方法就行
    /**
     * 通知包裹了目标方法,在目标方法调用之前和之后执行自定义的行为
     * ProceedingJoinPoint切入点可以获取切入点方法上的名字、参数、注解和对象
     * @param joinPoint
     */
    @Around("SystemControllerLog() && @annotation(systemControllerLog)")
  public Result doAfterReturning(ProceedingJoinPoint joinPoint, SystemControllerLog systemControllerLog) throws Throwable {
        logger.info("设置日志信息存储到表中!");
        //joinPoint.proceed() 结果集
        //参数数组
        Object[] args = joinPoint.getArgs();
        //请求参数数据
        String requestJson = JSONUtil.toJsonStr(args);
        //方法名
        String methodName = joinPoint.getSignature().getName();
        //得到request
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //得到token
        String token = request.getHeader("token");
        String userId = JWT.decode(token).getAudience().get(0);
        User user = userService.getById(userId);
        logger.info("得到用户信息:"+user.toString());
        //写入数据库操作日志
        Systemlog systemlog = new Systemlog();
        systemlog.setUserId(user.getUid());
        systemlog.setUserName(user.getUname());
        systemlog.setOperate(systemControllerLog.operate());
        systemlog.setModule(systemControllerLog.module());
        systemlog.setCreateTime(new Date());
        //存入返回的结果集 joinPoint.proceed()
        Result proceed = (Result) joinPoint.proceed();
        systemlog.setResult(JSONUtil.toJsonStr(joinPoint.proceed()));
        //保存
       saveSystemLog(systemlog);

       return proceed;

    }

}

5.Use the controller

 @GetMapping("/userListPage")
 @SystemControllerLog(operate = "用户查询",module = "用户管理")
 public Result findUserList( @RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam String username,
                                @RequestParam String loveValue,
                                @RequestParam String address) {}
  @PostMapping("/addOrUpdate")
  @SystemControllerLog(operate = "用户修改或者添加",module = "用户管理")
  public Result addOrUpdateUser(@RequestBody User user){}

6. Database records

How SpringBoot uses AOP to record interface operation logs

The above is the detailed content of How SpringBoot uses AOP to record interface operation logs. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment