
execution([수식어] 리턴타입 [클래스이름], 이름(파라미터))execution(public Integer [classpath].advice.*.*(*))execution(* [classpath].annotation..stu*(..))[ContextConfiguration.java]
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true) // AOP 적용
public class ContextConfiguration {
}
[LoggingAspect.java]
@Aspect
@Component
public class LoggingAspect {
@Pointcut("execution(* claspath.aop.*Service.*(..))")
public void logPointcut() {}
// 설명. 1. Before Advice
// @Before("execution(* [classpath].aop.*Service.*(..))")
@Before("LoggingAspect.logPointcut()")
public void logBefore(JoinPoint joinPoint) {
System.out.println("Before joinPoint.getTarget(): " + joinPoint.getTarget());
System.out.println("Before joinPoint.getSignature: " + joinPoint.getSignature());
if(joinPoint.getArgs().length > 0) {
System.out.println("Before joinPoint.getArgs()[0]: " + joinPoint.getArgs()[0].getClass());
}
}
// 설명. 2. After Advice
@After("LoggingAspect.logPointcut()")
public void logAfter(JoinPoint joinPoint) {
System.out.println("After joinPoint.getTarget(): " + joinPoint.getTarget());
System.out.println("After joinPoint.getSignature(): " + joinPoint.getSignature());
if(joinPoint.getArgs().length > 0) {
System.out.println("After joinPoint.getArgs()[0]: " + joinPoint.getArgs()[0]);
}
}
// 설명. 3. AfterReturning Advice
@AfterReturning(pointcut="logPointcut()", returning="result")
public void logAfterReturning(JoinPoint joinPoint, Object result) {
System.out.println("After Returning result: " + result);
if (result != null && result instanceof List) {
((List<MemberDTO>) result).add(
new MemberDTO(3L, "반환 값 가공")
);
}
}
// 설명. 4. AfterThrowing Advice
@AfterThrowing(pointcut="logPointcut()", throwing="exception")
public void logAfterThrowing(Throwable exception) {
System.out.println("After Throwing exception: " + exception);
}
// 설명. 5. Around Advice
@Around("logPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("Around Before: " + joinPoint.getSignature().getName());
Object result = joinPoint.proceed(); // 타겟 메소드 동작
System.out.println("Around After: " + joinPoint.getSignature().getName());
System.out.println("result = " + result);
return result;
}
}
