BeforeAdvice와 AroundAdvice는 스프링 AOP(Aspect-Oriented Programming)에서 사용하는 두 가지 종류의 어드바이스(Advice)입니다. 어드바이스는 애플리케이션의 메인 로직에 추가적인 동작을 삽입할 수 있는 코드 조각을 의미합니다. 각각의 어드바이스는 타겟 메소드의 실행 시점에 따라 다르게 동작합니다.
BeforeAdvice는 타겟 메소드가 실행되기 직전에 실행되는 어드바이스입니다. 주로 로깅, 보안 체크, 유효성 검사 등의 사전 작업을 수행하는 데 사용됩니다.
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class MyBeforeAdvice implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println("Before method: " + method.getName());
}
}
위 예제에서 MyBeforeAdvice는 MethodBeforeAdvice 인터페이스를 구현하며, 타겟 메소드가 호출되기 전에 실행됩니다.AroundAdvice는 타겟 메소드의 실행 전후에 모두 실행되는 어드바이스입니다. 이 어드바이스는 타겟 메소드의 호출을 감싸며, 타겟 메소드의 실행 전후에 원하는 로직을 수행할 수 있습니다. 심지어 타겟 메소드의 실행 여부를 결정하거나 결과를 변경할 수도 있습니다.
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class MyAroundAdvice implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("Before method: " + invocation.getMethod().getName());
// 타겟 메소드 호출
Object result = invocation.proceed();
System.out.println("After method: " + invocation.getMethod().getName());
return result;
}
}
위 예제에서 MyAroundAdvice는 MethodInterceptor 인터페이스를 구현하며, invoke 메소드 내에서 타겟 메소드의 실행 전후에 로직을 추가합니다. invocation.proceed()가 타겟 메소드를 호출하는 부분입니다.AfterAdvice는 스프링 AOP(Aspect-Oriented Programming)에서 사용되는 어드바이스 유형 중 하나로, 타겟 메소드가 실행된 후에 실행되는 코드를 정의하는 데 사용됩니다. 이를 통해 메소드 실행이 완료된 후에 실행해야 하는 부가 작업들을 처리할 수 있습니다.
AfterAdvice에는 다음과 같은 세 가지 주요 형태가 있습니다:
AfterReturningAdvice:
package ex05.aop;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class LogPrintAfterReturningAdvice implements AfterReturningAdvice {
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("AfterReturning Advice: 메소드 실행 후");
System.out.println("반환 값: " + returnValue);
}
}
AfterThrowingAdvice:
package ex05.aop;
import org.springframework.aop.ThrowsAdvice;
public class LogPrintThrowingAdvice implements ThrowsAdvice {
public void afterThrowing(Method method, Object[] args, Object target, Exception e) {
System.out.println("AfterThrowing Advice: 예외 발생 후");
System.out.println("예외 메시지: " + e.getMessage());
}
}
After (Finally) Advice:
package ex05.aop;
import org.springframework.aop.AfterAdvice;
public class LogPrintAfterFinallyAdvice implements AfterAdvice {
public void after(Method method, Object[] args, Object target) {
System.out.println("AfterFinally Advice: 메소드 종료 후 (성공/실패 무관)");
}
}
Spring XML 설정에서 AfterAdvice를 적용하는 방법은 다음과 같습니다:
<aop:config>
<aop:aspect id="aspect" ref="logPrintAfterAdvice">
<!-- 특정 메소드 호출 후에 Advice 실행 -->
<aop:pointcut id="pointCut" expression="execution(* ex05.aop.ICalc.*(..))"/>
<aop:after method="after" pointcut-ref="pointCut"/>
</aop:aspect>
</aop:config>