package com.example.aop;
import lombok.AllArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Aspect
@Component
@AllArgsConstructor
public class MethodStartEndAspect {
private final Map<String, Logger> map = new HashMap<>();
@Before("execution(* com.example..*(..))")
public void start(JoinPoint joinPoint) {
String loggerName = joinPoint.getSignature().getDeclaringType().getSimpleName();
Logger logger;
if (map.containsKey(loggerName)) {
logger = map.get(loggerName);
} else {
logger = LoggerFactory.getLogger(joinPoint.getSignature().getDeclaringType().getSimpleName());
map.put(loggerName, logger);
}
logger.info("START {}#{}", joinPoint.getSignature().getDeclaringType().getName(), joinPoint.getSignature().getName());
}
@After("execution(* com.example..*(..))")
public void end(JoinPoint joinPoint) {
String loggerName = joinPoint.getSignature().getDeclaringType().getSimpleName();
Logger logger = map.get(loggerName);
logger.info("END {}#{}", joinPoint.getSignature().getDeclaringType().getName(), joinPoint.getSignature().getName());
}
}