Spring

[Spring] 스프링 AOP(3) - @Aspect 기반

재담 2022. 2. 19. 21:26

@Aspect 어노테이션을 이용한 AOP

@Aspect 어노테이션을 이용한 AOP 구현은 XML 방식과 별로 다르지 않다. Aspect 클래스에 @Aspect 어노테이션만 적용하면 된다. 그리고 Pointcut도 Aspect 클래스에서 정의한다.

@Aspect
public class Profile {

    @Pointcut("execution(public * com.mypackage..*(..))")
    private void profileTarget() {
    }

    @Around("profileTarget()")
    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");
        }
    }
}

위 코드에서 @Aspect 어노테이션을 사용했는데, @Aspect 어노테이션이 적용된 클래스는 Advice 구현 메서드나 Pointcut 정의를 포함할 수 있게 된다. Advice의 타깃으로는 Pointcut의 메서드 이름을 지정하면 된다.(위의 경우 profileTarget() 메서드)

 

다음으로는 설정 정보에 Aspect 클래스를 빈으로 등록해야 한다.

<?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">

   <aop:aspectj-autoproxy />

    <!-- Aspect 클래스를 빈으로 등록 -->
    <bean id="traceAspect" class="com.mypackage.aop.Profile" />
    
    <!-- 이하 생략 -->
    ...
</beans>

위 설정에서 <aop:aspectj-autoproxy> 태그를 사용했는데, 이는 @Aspect 어노테이션이 적용된 빈 객체를 Aspect로 사용할 수 있게 해 준다. @Configuration 기반 자바 설정을 이용한다면 @EnableAspectJAutoProxy를 설정한다.


Reference

  • 웹 개발자를 위한 Spring 4.0 프로그래밍 (최범균 저)