如何利用自定义注解实现一个日志记录功能?请给出一个具体的代码实现方案。

import java.lang.annotation.*;

/**
 * 自定义注解用于标记需要记录日志的方法
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Loggable {
    String value() default "";
}

/**
 * 切面类,通过AOP拦截标记了@Loggable的方法并记录日志
 */
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {

    // 定义切入点,标记了@Loggable的方法
    @Pointcut("@annotation(com.example.Loggable)")
    public void loggableMethod() {}

    // 环绕通知,记录方法执行的日志
    @Around("loggableMethod()")
    public Object logMethodExecution(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("开始执行方法: " + methodName);
        
        // 记录方法参数
        Object[] args = joinPoint.getArgs();
        if (args != null && args.length > 0) {
            System.out.println("方法参数:");
            for (Object arg : args) {
                System.out.println(arg);
            }
        }
        
        // 执行方法
        Object result = joinPoint.proceed();
        
        // 记录方法返回值
        System.out.println("方法返回值: " + result);
        System.out.println("方法执行结束: " + methodName);
        
        return result;
    }
}

/**
 * 示例服务类,使用@Loggable注解标记需要记录日志的方法
 */
@Service
public class ExampleService {

    @Loggable("记录用户信息")
    public String getUserInfo(String userId) {
        return "用户信息: " + userId;
    }
}

/**
 * 主程序,测试日志记录功能
 */
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

实现说明

  1. 自定义注解 @Loggable

    • 通过 @Retention(RetentionPolicy.RUNTIME) 指定注解在运行时可用。
    • 通过 @Target(ElementType.METHOD) 指定该注解只能用于方法上。
    • 注解的 value 属性可以自定义日志描述。
  2. 切面类 LoggingAspect

    • 使用 @Aspect 标记为切面类。
    • 定义切入点 loggableMethod(),拦截所有标记了 @Loggable 的方法。
    • 通过 @Around 环绕通知实现对方法的拦截,记录方法执行前后的日志。
    • 在日志中记录方法名称、参数和返回值。
  3. 示例服务类 ExampleService

    • 在 getUserInfo 方法上使用 @Loggable 注解,标记该方法需要记录日志。
  4. 主程序 Application

    • 启动 Spring Boot 应用程序,触发切面逻辑。

示例运行结果

当调用 ExampleService 的 getUserInfo 方法时,控制台会输出以下日志:

开始执行方法: getUserInfo
方法参数:
123
方法返回值: 用户信息: 123
方法执行结束: getUserInfo

注意事项

  • 确保项目中已引入 Spring AOP 依赖(如 spring-boot-starter-aop)。
  • 注解和切面类需要在组件扫描的路径下才能生效。
  • 通过 AOP 实现日志功能时,避免在切面中抛出异常,以免影响业务逻辑。