Spring
[Spring] 스프링 AOP(2) - XML 기반
재담
2022. 2. 19. 00:41
XML 기반의 POJO 클래스를 이용한 AOP 구현
aop 네임스페이스를 사용하려면 <beans> 루트 태그에 aop 네임스페이스에 대한 스키마를 지정해야 한다.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 이하 생략 -->
...
</beans>
먼저 공통 기능을 제공할 Advice 구현 클래스는 다음과 같다.
import org.aspectj.lang.ProceedingJoinPoint;
public class Profiler {
public Object trace(ProceedingJoinPoint joinPoint) throws Throwable {
String signatureString = joinPoint.getSignature().toShortString();
System.out.println(signatureString + " 시작");
long start = System.currentTimeMillis();
try {
Object result = joinPoint.proceed();
return result;
} finally {
long finish = System.currentTimeMillis();
System.out.println(signatureString + " 종료");
System.out.println(signatureString + " 실행 시간 : " + (finish - start) + "ms");
}
}
}
위 코드에서 Profiler 클래스가 Around를 위한 것인지 Before을 위한 것인지 명시되어 있지 않다. trace() 메서드는 ProceedingJoinPoint 타입의 파라미터를 전달받아서 해당 Advice에 맞는 공통 기능을 구현하게 된다.
위의 trace() 메서드는 Advice가 적용될 대상 객체를 호출(Object result = joinPoint.proceed(); 라인)하기 전과 후에 시간을 구해서(Around Advice) 대상 객체의 메서드 실행 시간을 출력한다. 일단 이 정도만 알고 넘어가자.
앞서 aop 네임스페이스의 XML 스키마를 지정했다면, <aop:config> 태그를 사용하여 AOP 관련 정보를 설정할 수 있다.
<bean id="profiler" class="com.mypackage.aop.Profiler"/>
<!-- Aspect 설정: Advice를 어떤 Pointcut에 적용할 지 설정 -->
<aop:config>
<aop:aspect id="traceAspect" ref="profiler">
<aop:pointcut id="publicMethod" expression="execution(public * com.mypackage..*(..))"/>
<aop:around pointcut-ref="publicMethod" method="trace"/>
</aop:aspect>
</aop:config>
<bean id="memberService" class="com.mypackage.member.MemberServiceImpl"/>
<!-- 이하 생략 -->
...
aop 네임스페이스의 각 태그는 다음과 같은 정보를 설정한다.
- <aop:config> : AOP 설정 정보임을 표현
- <aop:aspect> : Aspect를 설정
- <aop:pointcut> : Pointcunt을 설정
- <aop:around> : Around Advice를 설정(Around 외에도 많다.)
<aop:aspect> 태그의 ref 속성은 Aspect의 공통 기능을 제공할 빈을 설정할 때 사용된다. 위 설정의 내용을 간단히 말하면 다음과 같다.
- 이름이 "traceAspect"인 Aspect는 MemberServiceImpl 클래스의 public 메서드에 대해 Around Advice로 적용됨
- "traceAspect"의 구현으로 사용되는 profiler 빈의 "trace" 메서드를 통해 공통 기능을 제공함
Reference
- 웹 개발자를 위한 Spring 4.0 프로그래밍 (최범균 저)