스프링의 부가기능 | AOP

Faithful Dev·2025년 2월 24일

스프링 프레임워크

목록 보기
7/20

AOP(Aspect-Oriented Programming, 관점 지향 프로그래밍)핵심 비즈니스 로직과 부가적인 기능(공통 관심사, Cross-Cutting Concern)을 분리하여 코드의 모듈성을 향상시키는 프로그래밍 기법이다.

핵심 개념

  • OOP(객체 지향 프로그래밍): 클래스 단위로 관심사를 분리
  • AOP(관점 지향 프로그래밍): 횡단 관심사(Logging, Security, Transaction 등)를 모듈화

예제: AOP가 필요한 상황

public class UserService {
	public void createUser(String name) {
    	System.out.println("User created: " + name); // 핵심 기능
        System.out.println("로그 기록: 사용자 생성"); // 공통 관심사 (AOP로 분리 가능)
	}
}

→ AOP를 사용하면 로깅 코드를 핵심 비즈니스 로직에서 분리할 수 있다.


주요 개념

용어설명
Aspect부가 기능을 모듈화한 것 (e.g., 로깅, 트랜잭션 관리)
Join PointAOP가 적용될 수 있는 지점 (메서드 실행, 객체 생성 등)
Advice실행할 부가 기능 (Before, After, Around 등)
PointcutAdvice를 적용할 메서드 지정 (표현식 사용)
WeavingAdvice를 대상 객체에 적용하는 과정 (컴파일 시, 런타임 시)

적용 방법

@Aspect@Around를 이용한 AOP 구현

AOP 설정

import org.aspectj.lang.annotation.*;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;

@Aspect // AOP 기능을 가진 클래스
@Component // 스프링 빈으로 등록
public class LoggingAspect {
	
    @Around("execution(* com.example.service.*.*(..))") // 서비스 계층 모든 메서드에 적용
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
    	long start = System.currentTimeMillis();
        Object result = joinPoint.proceed(); // 실제 메서드 실행
        long end = System.currentTimeMillis();
        System.out.println(joinPoint.getSignature() + " 실행 시간: " + (end - start) + "ms");
        return result;
	}
}
  • @Aspect: AOP 클래스 선언
  • @Around("execution(* 패키지.클래스.메서드(..))"): 대상 메서드 지정
  • joinPoint.proceed(): 실제 비즈니스 로직 실행

@Before@After를 이용한 AOP 적용

메서드 실행 전/후에 로깅 추가

@Aspect
@component
public class LoggingAspect {
	
    @Before("execution(* com.example.service.UserService.*(..))")
    public void beforeAdvice() {
    	System.out.println("메서드 실행 전 - 로그 기록");
	}
    
    @After("execution(* com.example.service.UserService.*(..))")
    public void afterAdvice() {
    	System.out.println("메서드 실행 후 - 로그 기록");
	}
}
  • @Before: 메서드 실행 전에 실행
  • @After: 메서드 실행 후에 실행

@Pointcut으로 중복 제거

공통 관심사 정의

@Aspect
@Component
public class LoggingAspect {
	
    @Pointcut("execution(* com.example.service.*.*(..))")
    public void sericeMethods() {}
    
    @Before("serviceMethods()")
    public void beforeAdvice() {
    	System.out.println("메서드 실행 전 - 로그 기록");
	}
    
    @After("serviceMethods()")
    public void afterAdvice() {
    	System.out.println("메서드 실행 후 - 로그 기록");
	}
}
  • @Pointcut: 여러 Advice에서 재사용 가능

장점

  • 핵심 비즈니스 로직과 공통 관심사를 분리: 코드가 깔끔해짐
  • 코드 중복 제거: 유지보수 용이
  • 트랜잭션 관리, 로깅, 보안 등에 효과적

정리

  • AOP(Aspect-Oriented Programming)은 핵심 로직과 공통 관심사를 분리하는 기법
  • 주요 개념: Aspect, Advice, Join Point, Pointcut, Weaving
  • 스프링 AOP는 @Aspect, @Before, @After, @Around 등을 사용하여 구현
  • 로깅, 트랜잭션 관리, 보안 등에 효과적으로 활용 가능

AOP를 활용하면 더 유지보수하기 쉬운 코드를 만들 수 있다.

profile
Turning Vision into Reality.

0개의 댓글