Logging using AOP (Aspect Oriented Programming) and custom annotations

1. Import dependencies

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

2. Define custom annotations 

@Target (acting on a class, field or method)

@Rentention (generally choose Runntime)

@Retention(RetentionPolicy.RUNTIME)//定义注解的使用范围,编译时,还是运行时。。。
@Target(ElementType.METHOD)//定义注解用在哪里class,method。。。
public @interface Login {
    String value() default "";
}

3. Notes are pasted where needed

4. Annotations for point-cutting expressions

scope pointcut expression pointcut expression
acts on the field get
act on the method @annotation Can only be used to select methods with specific annotations as join points Instead execution , it can be matched according to more method features. Such as parameters, method names
acts on the class within

@Around, @Before and @AfterReturning are three annotations at the method level.

Among them, @Around is before and after method execution. If the method execution fails, you can catch the exception, handle it yourself, or throw it. If thrown, no subsequent code is executed.

@Before before the method is executed

@AfterReturning is after the method returns successfully (if the execution fails, an exception is thrown, and the aspect method is not executed)

The following uses custom annotations and global logging as an example to show the usage of @Around annotations on methods.

@Aspect
@Component
public class SystemLogAspect {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(SystemLogAspect.class);

    @Around("@annotation(com.example.annotation.SystemLog)")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();

        SystemLog systemLog = method.getAnnotation(SystemLog.class);
        String message = systemLog.value();

        Long startTime = System.currentTimeMillis();
        Object result;
        try {
            result = joinPoint.proceed();
        } catch (Throwable throwable) {
            throw throwable;
        } finally {
            Long endTime = System.currentTimeMillis();
            long time = endTime - startTime;
            
            LOGGER.info("[SystemLog] {}.{}: {}ms", 
                joinPoint.getTarget().getClass().getName(), 
                method.getName(), time);
        }
        return result;
    }
}

Guess you like

Origin blog.csdn.net/tomorrow9813/article/details/131412127