안녕하세요.
이번 글에서는 관점 지향 프로그래밍을 의미하는 AOP에 대해 알아보겠습니다.
public void A() {
System.out.println("hello");
methodA();
System.out.println("bye");
}
public void B() {
System.out.println("hello");
methodB();
System.out.println("bye");
}
두 개의 메서드는 hello, bye 출력이라는 동일한 코드를 가지고 있습니다. 유사한 메서드가 더 많이 만들어지고 코드를 수정해야하는 경우가 생긴다면, 코드를 유지관리하기 매우 비효율적일 것입니다.
이렇게 핵심적인 기능이 아닌 중간마다 사용되어 삽입되어야 할 기능들에 대한 관심사들을 횡단관심사(Cross-Cutting Concerns)라고 합니다.
예를 들어 로깅, 보안, 트랜잭션 처리 등 비즈니스 핵심 사항이 아닌 다양한 횡단관심사가 존재할 수 있습니다.
2. AOP 주요 개념
4. 예제 (in Spring Framework)
1) AOP 적용 이전
package com.example.aop.controller;
import com.example.aop.dto.User;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class RestApiController {
@GetMapping("/get/{id}")
public String get(@PathVariable Long id, @RequestParam String name) {
System.out.println("get method");
System.out.println("get method : " + id);
System.out.println("get method : " + name);
return id + " " + name;
}
}
출력 결과
2) AOP 적용
package com.example.aop.controller;
import com.example.aop.dto.User;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class RestApiController {
@GetMapping("/get/{id}")
public String get(@PathVariable Long id, @RequestParam String name) {
return id + " " + name;
}
}
package com.example.aop.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Aspect // aop 로 동작하기 위함 (class 에 설정)
@Component // [DI] Spring 에서 관리한다.
public class ParameterAop {
@Pointcut("execution(* com.example.aop.controller..*.*(..))") // 메서드에 설정
private void cut() {
}
@Before("cut()") // cut()이라는 Pointcut 실행되기 전에 메서드를 실행
public void before(JoinPoint joinPoint) {
// methodSignature 객체를 통해 method 이름을 알 수 있다
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
System.out.println(method.getName());
Object[] args = joinPoint.getArgs();
for(Object obj : args) {
System.out.println("type: " + obj.getClass().getSimpleName());
System.out.println("value : " + obj);
}
}
@AfterReturning(value = "cut()", returning = "returnObj")
public void afterReturn(JoinPoint joinPoint, Object returnObj) {
System.out.println("return obj");
System.out.println(returnObj);
}
}
이번 글에서는 관점 지향 프로그래밍을 의미하는 AOP에 대해 알아보았습니다.
감사합니다~