Mastering Spring Boot AOP: Unified Web Request Logging Made Simple

This tutorial explains the fundamentals of Spring AOP, introduces key terminology and pointcut expressions, demonstrates how to configure various advice types, and provides a complete Spring Boot example that uses an aspect to automatically record web request logs with minimal code changes.

BiCaiJia Technology Team
BiCaiJia Technology Team
BiCaiJia Technology Team
Mastering Spring Boot AOP: Unified Web Request Logging Made Simple

Spring Boot AOP Overview

Spring’s two core features are AOP (Aspect‑Oriented Programming) and IoC (Inversion of Control). AOP allows cross‑cutting concerns such as transaction management, logging, and resource handling to be modularized without altering the original business logic.

Key AOP Concepts

Aspect : a modular unit of a concern that can affect multiple classes.

Joinpoint : a specific point during program execution, typically a method invocation.

Advice : the action taken at a joinpoint (e.g., before, after, around).

Pointcut : an expression that selects joinpoints where advice should be applied.

Introduction : adds new methods or fields to existing classes.

Target Object : the object being advised.

AOP Proxy : the proxy created by Spring (JDK dynamic proxy or CGLIB) to implement the aspect.

Weaving : the process of linking aspects with other application types or objects, performed at compile time, load time, or runtime.

Pointcut Expressions

A pointcut consists of a signature and an expression. The most common syntax is the execution designator:

execution([visibility] returnType declaringType?.methodName(parameterPattern) [throwsPattern])

Wildcards can be used: * – matches any character sequence. .. – matches any number of packages or parameters. + – matches a type and its subclasses.

Logical operators: &&, ||, !.

Supported Advice Types

@Before

– runs before the matched method. @AfterReturning – runs after the method returns successfully. @AfterThrowing – runs after the method throws an exception. @After – runs after the method finishes (whether normally or exceptionally). @Around – wraps the method execution, allowing control over invocation, parameters, and return value.

Example: Unified Web Request Logging

The following example shows how to use AOP in a Spring Boot project to automatically log web requests.

Project Setup

Add the AOP starter dependency to pom.xml:

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

Controller

@RestController
public class HelloController {
    @RequestMapping("/sysLog")
    public String sysLog(String name, int state) {
        state = 6 / state;
        for (int i = 0; i < 10000; i++) {
            int a = i * i - i - 1;
            name = name + a;
        }
        name = "haha";
        return "name " + name + "---" + state;
    }
}

Log Entity and Service

public class SysLogEntity implements Serializable {
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String username;
    private String operation;
    private String method;
    private String params;
    private Long time;
    private String ip;
    private Date createDate;
    // getters and setters omitted for brevity
}

public interface SysLogService {
    int save(SysLogEntity sysLogEntity);
}

@Service
public class SysLogServiceImpl implements SysLogService {
    @Override
    public int save(SysLogEntity sysLogEntity) {
        System.out.println("Saving system log: " + JSON.toJSONString(sysLogEntity));
        return 0;
    }
}

Custom Annotation

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
    String value() default "";
}

Logging Aspect

@Aspect
@Component
public class WebLogAspect {
    @Autowired
    private SysLogService sysLogService;

    @Pointcut("@annotation(com.wuyou.aop.annotation.SysLog)")
    public void logPointCut() {}

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        Object result = point.proceed();
        long time = System.currentTimeMillis() - beginTime;
        saveSysLog(point, time);
        return result;
    }

    private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SysLogEntity sysLog = new SysLogEntity();
        SysLog syslog = method.getAnnotation(SysLog.class);
        if (syslog != null) {
            sysLog.setOperation(syslog.value());
        }
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");
        Object[] args = joinPoint.getArgs();
        try {
            String params = JSON.toJSONString(args[0]);
            sysLog.setParams(params);
        } catch (Exception e) { }
        sysLog.setUsername("systemUser001");
        sysLog.setTime(time);
        sysLog.setCreateDate(new Date());
        sysLogService.save(sysLog);
    }
}

Running the Example

Start the Spring Boot application and access http://localhost:8080/sysLog?name=aaaaaa&state=6. The console will display the generated log entries, confirming that the aspect intercepts the request, measures execution time, and records the details automatically.

Project structure diagram
Project structure diagram

This example demonstrates a practical use of Spring AOP to achieve unified web request logging with minimal boilerplate code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AOPSpring BootaspectjWeb Logging
BiCaiJia Technology Team
Written by

BiCaiJia Technology Team

BiCaiJia Technology Team

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.