[AOP] AOP의 예시

POKUDING·2024년 6월 20일
post-thumbnail

AOP 예시

data를 제공하는 Repository와 비즈니스 로직을 갖고 있는 Service 를 만들고 Logging을 하는 관심사를 따로 만들어서 실행시켜보자

//Repository 코드
@Repository  
public class DataService1 {  
  
    public int[] retrieveData() {  
        return new int[] {11, 22, 33, 44, 55};  
    }  
}
//Service 코드
@Service  
public class BusinessService1 {  
  
    private final DataService1 dataService1;  
  
    public BusinessService1(DataService1 dataService1) {  
        this.dataService1 = dataService1;  
    }  
  
    public int calculateMax() {  
        int[] data = dataService1.retrieveData();  
        return Arrays.stream(data).max().orElse(0);  
    }  
}
//로깅 코드
import org.aspectj.lang.JoinPoint;  
import org.aspectj.lang.annotation.Aspect;  
import org.aspectj.lang.annotation.Before;  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
import org.springframework.context.annotation.Configuration;  
  
@Configuration  
@Aspect  
public class LoggingAspect {  
  
    private Logger logger = LoggerFactory.getLogger(this.getClass());  
  
    //Pointcut - When?  
    //execution(* PACKAGE.*.*(..))    
    @Before("execution(* com.junhyupa.learnspringaop.aopexample.*.*.*(..))")  
    public void logMethodCall(JoinPoint joinPoint) {  
        logger.info("Before Aspect - {} is called with arguments: {}", joinPoint, joinPoint.getArgs());  
    }  
}
//실행코드
@SpringBootApplication  
public class LearnSpringAopApplication implements CommandLineRunner {  
  
    private final Logger logger = LoggerFactory.getLogger(this.getClass());  
    private final BusinessService1 businessService1;  
  
    public LearnSpringAopApplication(BusinessService1 businessService1) {  
        this.businessService1 = businessService1;  
    }  
    public static void main(String[] args) {  
        SpringApplication.run(LearnSpringAopApplication.class, args);  
    }  
  
    @Override  
    public void run(String... args) throws Exception {  
        logger.info("value returned is {}", businessService1.calculateMax());  
    }  
}
실행 결과

특정 패키지의 메소드가 실행되기 전에 로깅을 하도록 세팅하고 실행시킨 로그이다.
로그를 살펴보면 메소드가 불린 순서대로 calculateMax 가 먼저 로깅되고 retrieveData 가 그다음 그리고 마지막으로 실행한 결과가 화면에 보이는 것을 알 수 있다.

여기서 Advice는 로그를 찍는 로직 부분이고 Point Cut은 @Before 어노테이션 내의
com.junhyupa.learnspringaop.aopexample.*.*.*(..) 부분이다.
그리고 Join Point를 로그에 찍었다.

이처럼 Join Point가 실행될 때 Advice가 실행되도록 하여 관심사를 분리하는 방식을 AOP라고 한다.

profile
세상을 바꾸는 꿈을 꾸는 개발자

0개의 댓글