스프링 AOP: 스키마 기반 전/후 어드바이스 구현

스프링(Spring) 프레임워크는 AOP(Aspect-Oriented Programming)를 구현하기 위한 두 가지 주요 방식을 제공합니다. 하나는 스키마 기반(Schema-based) 방식이고, 다른 하나는 AspectJ 기반 방식입니다. 이 문서에서는 스키마 기반 AOP를 사용하여 메서드 실행 전후에 특정 로직을 삽입하는 전(Before) 및 후(After) 어드바이스(Advice) 구현 방법을 다룹니다.

스키마 기반 AOP 개요

  • 스키마 기반 AOP: 각 어드바이스는 특정 인터페이스나 클래스를 구현해야 합니다. 스프링 설정 파일에서 <aop:config> 요소를 사용하여 AOP를 구성합니다.
  • AspectJ 기반 AOP: 어드바이스가 별도의 인터페이스를 구현할 필요가 없습니다. <aop:config> 요소의 하위 태그인 <aop:aspect>를 통해 설정합니다.

이 가이드에서는 스키마 기반 방식에 중점을 두어 예제를 구현합니다.

스키마 기반 AOP 구현 단계

1. 필요한 의존성 추가

스프링 핵심 라이브러리 외에 스프링 AOP 관련 JAR 파일이 필요합니다. 일반적으로 spring-aop 및 aspectjweaver 등의 의존성을 프로젝트에 추가해야 합니다.

2. 어드바이스 클래스 정의

전 어드바이스와 후 어드바이스는 각각 MethodBeforeAdvice와 AfterReturningAdvice 인터페이스를 구현해야 합니다.

전 어드바이스 구현

MethodBeforeAdvice 인터페이스의 before 메서드를 오버라이드하여 대상 메서드 실행 전에 수행할 로직을 정의합니다.

package dev.spring.aop.advice;

import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;

public class LoggingBeforeAdvice implements MethodBeforeAdvice {

    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("--- [LoggingBeforeAdvice] 메서드 실행 전 로깅 ---");
        System.out.println("대상 메서드: " + method.getName());
        if (args != null && args.length > 0) {
            System.out.println("전달된 인자: " + java.util.Arrays.toString(args));
        }
    }
}

before 메서드의 파라미터는 다음과 같습니다:

  • method: 실행될 대상 메서드의 Method 객체.
  • args: 대상 메서드에 전달된 인자 배열.
  • target: 대상 메서드를 포함하는 객체 인스턴스.
후 어드바이스 구현

AfterReturningAdvice 인터페이스의 afterReturning 메서드를 오버라이드하여 대상 메서드가 성공적으로 반환된 후에 수행할 로직을 정의합니다.

package dev.spring.aop.advice;

import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;

public class LoggingAfterAdvice implements AfterReturningAdvice {

    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("--- [LoggingAfterAdvice] 메서드 성공적 반환 후 로깅 ---");
        System.out.println("대상 메서드: " + method.getName());
        System.out.println("반환 값: " + (returnValue != null ? returnValue.toString() : "void"));
    }
}

afterReturning 메서드의 파라미터는 다음과 같습니다:

  • returnValue: 대상 메서드가 반환한 값. (메서드의 반환 타입이 void일 경우 null)
  • method: 실행된 대상 메서드의 Method 객체.
  • args: 대상 메서드에 전달된 인자 배열.
  • target: 대상 메서드를 포함하는 객체 인스턴스.

3. AOP 설정 구성 (XML)

스프링 설정 파일(예: applicationContext.xml)에서 어드바이스와 대상 객체를 빈으로 등록하고 AOP 설정을 구성합니다.

  • AOP 네임스페이스를 선언합니다.
  • 어드바이스 클래스를 스프링 빈으로 등록합니다.
  • <aop:config> 내에서 <aop:pointcut>으로 어드바이스를 적용할 지점(join point)을 정의합니다.
  • <aop:advisor>를 사용하여 어드바이스와 포인트컷을 연결합니다.

다음은 대상 서비스 클래스입니다:

package dev.spring.aop.target;

public class SimpleServiceTarget {

    public void processData() {
        System.out.println("[SimpleServiceTarget] 데이터 처리 로직 실행 중...");
    }

    public String fetchData(String query) {
        System.out.println("[SimpleServiceTarget] 데이터 '" + query + "' 조회 로직 실행 중...");
        return "조회된 데이터: " + query.toUpperCase();
    }
}

XML 설정 예시:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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">

    <!-- 어드바이스 구현체 빈 등록 -->
    <bean id="beforeLogger" class="dev.spring.aop.advice.LoggingBeforeAdvice"/>
    <bean id="afterLogger" class="dev.spring.aop.advice.LoggingAfterAdvice"/>

    <!-- 대상 서비스 빈 등록 -->
    <bean id="myService" class="dev.spring.aop.target.SimpleServiceTarget"/>

    <!-- AOP 설정 -->
    <aop:config>
        <!-- 포인트컷 정의: SimpleServiceTarget 클래스의 모든 메서드에 대해 적용 -->
        <aop:pointcut id="serviceMethods" expression="execution(* dev.spring.aop.target.SimpleServiceTarget.*(..))"/>

        <!-- 어드바이스와 포인트컷 연결 (어드바이저) -->
        <aop:advisor advice-ref="beforeLogger" pointcut-ref="serviceMethods"/>
        <aop:advisor advice-ref="afterLogger" pointcut-ref="serviceMethods"/>
    </aop:config>

</beans>

expression 속성의 execution(* dev.spring.aop.target.SimpleServiceTarget.*(..))는 dev.spring.aop.target.SimpleServiceTarget 클래스 내의 모든 리턴 타입, 모든 메서드 이름, 모든 파라미터를 가진 메서드를 포인트컷으로 지정한다는 의미입니다.

4. AOP 적용 테스트

스프링 컨텍스트를 로드하고 AOP가 적용된 대상 빈을 가져와 메서드를 호출하여 동작을 확인합니다.

package dev.spring.aop.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import dev.spring.aop.target.SimpleServiceTarget;

public class AopTestRunner {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        // AOP가 적용된 프록시 객체 반환
        SimpleServiceTarget service = context.getBean("myService", SimpleServiceTarget.class);

        System.out.println("\n--- processData() 호출 ---");
        service.processData();

        System.out.println("\n--- fetchData(\"sample\") 호출 ---");
        String result = service.fetchData("sample");
        System.out.println("메서드 반환 값: " + result);
    }
}

위 코드를 실행하면 processData() 및 fetchData("sample") 메서드가 호출되기 전후에 정의된 로깅 어드바이스가 실행되는 것을 확인할 수 있습니다.

태그: Spring AOP Schema-based AOP MethodBeforeAdvice AfterReturningAdvice Pointcut

10월 21일 22:34에 게시됨