Java_30_AOP

OngTK·2025년 9월 24일

Java

목록 보기
30/35

🔍 AOP (관점지향 프로그래밍)


📘 1. 정의

부가 기능을 하나로 모듈화하여 핵심 비즈니스 로직을 분리하는 프로그래밍 방식
AOP는 핵심 로직과 부가 기능을 분리하여 유지보수성과 재사용성을 높이는 데 매우 유용


🧭 2. 사용처

  • 로그(기록)
  • 트랜잭션
  • 보안(인증/권한)

📦 3. 설치

implementation 'org.springframework.boot:spring-boot-starter-aop'

⚙️ 4. 사용

4.1 AOP 클래스 어노테이션 주입

@Aspect         // 스프링 AOP container에 등록
@Component      // 스프링 bean container 등록

4.2 AOP 메소드 작성 및 @Before / @After 어노테이션 주입

  • @Before: Service 메소드 이전에 AOP 메소드 실행
  • @After: Service 메소드 이후에 AOP 메소드 실행
@Before()
public void check1() {
}

4.3 @Before / @After 어노테이션 조건 기재

@Before("execution( * AopService.*(..) )")

🔍 조건절 구성

@Before("execution( ① ②.③ ( ④ ) )")

  • ① 리턴 타입

    • * : 모든 리턴 타입
    • int : int 리턴 타입
  • ② 클래스 경로

    • 동일 패키지: 클래스명만 기재
    • 다른 패키지: Java 패키지 이하의 경로
  • ③ 메소드명

    • 대상 클래스 내의 메소드 이름
  • ④ 매개변수

    • (..) : 모든 매개변수에 대해 실행

➕ 추가 조건: && args(⑤)

@Before("execution( * AopService.*(..) ) && args(⑤) ")
  • ⑤ 바인딩할 매개변수 이름 정의
  • 오버라이드로 인해 동일한 메소드명에 대해 반환/매개변수로 구분 가능

4.4 @AfterReturning

@AfterReturning(value = "execution( * AopService.*(..) )", returning = "result")
public void afterReturn(Object result) {
    System.out.println("결과값: " + result);
}
  • value: 실행 조건절
  • returning: 결과값을 바인딩할 변수명

4.5 @Around

@Around("execution( * AopService.*(..) )")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
    System.out.println("메소드명: " + joinPoint.getSignature());
    System.out.println("매개변수: " + Arrays.toString(joinPoint.getArgs()));

    Object result = joinPoint.proceed(); // Service 메소드 실행
    return result; // 결과 반환
}

🧠 주요 개념

  • joinPoint: AOP 대상 객체
  • getSignature(): 실행될 메소드 정보
  • getArgs(): 매개변수 배열
  • proceed(): 실제 Service 메소드 실행 (예외 처리 필수)

profile
2025.05.~K디지털_풀스택 수업 수강중

0개의 댓글