AOP(Aspect Oriented Programming)是一种编程思想,它允许在运行时动态地修改对象的行为。在 Java 中,AOP 是使用 AspectJ 实现的。AspectJ 既可以在编译时织入代码,也可以在运行时动态织入代码。
我们可以使用 AOP 来拦截注解实现业务日志记录功能。具体实现过程如下:
1. 定义一个注解 `@Log`,用来标注需要记录日志的方法。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Log {
String value() default "";
}

2. 编写一个切面类 `LogAspect`,用来拦截被 `@Log` 注解标注的方法,并记录相应的日志。
@Component
@Aspect
public class LogAspect {
private static final Logger LOG = LoggerFactory.getLogger(LogAspect.class);
/**
* 拦截被 @Log 注解标注的方法,并记录相应的日志
*/
@Around("@annotation(com.example.demo.annotation.Log)")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
// 获取方法信息
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
// 获取注解信息
Log logAnnotation = method.getAnnotation(Log.class);
String value = logAnnotation.value();
// 记录日志
LOG.info("开始执行方法:{},注解信息:{}", methodSignature.getName(), value);
long startTime = System.currentTimeMillis();
Object result = joinPoint.proceed();
long endTime = System.currentTimeMillis();
Long totalTime = endTime - startTime;
LOG.info("方法:{} 执行完成,总共耗时:{} 毫秒", methodSignature.getName(), totalTime);
// 返回方法返回值
return result;
}
}3. 在需要记录日志的方法上加上 @Log 注解。
@Service
public class UserServiceImpl implements UserService {
@Override
@Log(value = "获取用户信息")
public User getUserById(Integer id) {
// 实现方法
}
// 其他方法
}
这样一来,当调用 `getUserById` 方法时,日志将会被拦截并记录。当然,在使用 AspectJ 时,需要在应用程序的配置文件中配置相应的切面表达式和切面对象等信息,并保证 AspectJ 的相关包已经被引入。