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

ttaho·2023년 3월 10일
0

Spring 기초

목록 보기
3/11

스프링 프레임워크에서 제공하는 AOP기능은 '중심적 관심사'와 '횡단적 관심사'를 분리하여 프로그램을 쉽게 만들 수 있게 도와준다.
내가 이해한대로 말해보자면,

한 메서드에서 메서드 실행전, 후의 시간을 재서 메서드의 실행시간을 구해야 한다고 하면, 모든 메서드에 시간을 재는 코드 작성한다고 많은 시간을 소모해야한다.
이때, AOP개념을 사용하여 시간을 재는 코드를 '횡단적 관심사'로 분리를 시키면 모든 메서드에 적용하지 않고, 한번만 작성하면 된다. 이를 구현해보자.

우선 aop기능을 사용하기 위해, aop관련 디펜던시를 추가해준다.

그리고, AOP 클래스를 생성시켜준다.

package com.example.demo.AOP;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;

@Aspect
@Component
public class SampleAspect {

//    @Before("execution(* com.example.demo.used.*Greet.*(..))")
    public void beforeAdvice(JoinPoint joinPoint){
        // 시작 부분 표시
        System.out.println("===== Before Advice =====");
        // 날짜를 출력
        System.out.println(new SimpleDateFormat("yyyy/MM/dd").format(new java.util.Date()));
        // 메서드 이름 출력
        System.out.println(String.format("메서드:%s", joinPoint.getSignature().getName()));
    }

//    @After("execution(* com.example.demo.used.*Greet.*(..))")
    public void afterAdvice(JoinPoint joinPoint){
        // 시작 부분 표시
        System.out.println("===== After Advice =====");
        // 날짜를 출력
        System.out.println(new SimpleDateFormat("yyyy/MM/dd").format(new java.util.Date()));
        // 메서드 이름 출력
        System.out.println(String.format("메서드:%s", joinPoint.getSignature().getName()));
    }

    @Around("execution(* com.example.demo.used.*Greet.*(..))")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        //시작 부분 표시
        System.out.println("===== Around Advice =====");
        System.out.println("▼▼▼ 처리전 ▼▼▼");
        // 지정한 클래스의 메서드 실행
        Object result = joinPoint.proceed();
        System.out.println("▲▲▲ 처리후 ▲▲▲");
        //반환값을 돌려줄 필요가 있는 경우에는 Object 타입의 반환값을 돌려줍니다.
        return result;

    }
}

@Aspect 어노테이션은 어드바이스를 기술하는 클래스(횡단적 관심사를 구현한 클래스)에 달아준다. 그리고 해당 인스턴스를 생성해야 하므로, @Component 어노테이션도 부여한다.
SampleAspect 클래스의 메서드는 위에부터 순서대로, 메서드 실행전에 호출하는 beforeAdvice, 메서드 실행후에 호출하는 afterAdvice, 메서드 실행전, 후에 호출되는 aroundAdvice 이다.
메인에서 실행되는 메서드는 Greet 메서드이다. 이를 표시하는것은 @Arter, @Before, @Around 뒤에있는 "execution( com.example.demo.used.Greet.*(..))"이다.
demo.used 패키지의 Greet으로 끝나는 클래스의 모든 메서드에 어드바이스를 적용한다는 뜻이다.

MorningGreet,EveningGreet 클래스의 Greeting 메서드에 적용한다.
현재는 @around, 즉 메서드 실행 전, 후에 어드바이스를 작성하므로, 아래와 같다.

요약

프로그램 개발 중, 동작 상황확인을 위해 여러 클래스에 System.out.println을 사용해 디버깅 로그를 출력해야 한다면, 이는 '횡단적 관심사' 이므로 AOP 기능을 사용하여 구현을 하면 모든 클래스에 System.out.println을 코드를 작성해 주지않고, AOP 클래스에 한번만 작성해주면 된다.

profile
백엔드 꿈나무

0개의 댓글