Spring AOP
2024. 7. 10. 18:06ㆍSpring Boot
AOP
Aspect Orinted Programming
관점 지향 프로그래밍이란 기존의 객체 지향 프로그래밍과는 달리
프로그래밍을 핵심적인 관점과 부가적인 관점으로 나누어
로그 처리 같은 부가적인 기능을 나누어 따로 관리하는 방법이다.
Spring Boot에서 비교적 간단하게 구현 할 수 있는데
우선 필요한 라이브러리를 implement해준다.
implementation 'org.springframework.boot:spring-boot-starter-aop'
그후 @Aspect를 이용하여 만들 AOP를 선언해주고
@Component로 Bean으로 등록 시켜주면 된다.
AOP는 Filter나 Interceptor과는 달리 URI가 아니라 메소드나 패키지 등을 기준으로 처리 전후에 실행 시킬 수 있다.
해당 예제는 com.example.demo.home 패키지 아래의 모든 메소드에 적용되게 구현을 하였다.
package com.example.demo.AOP;
import java.lang.reflect.Method;
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 lombok.extern.slf4j.Slf4j;
@Aspect
@Component
@Slf4j
public class aop_aspect {
@Pointcut("execution(* com.example.demo.home..*.*(..))")
private void cut() {}
// Pointcut에 의해 필터링된 경로로 들어오는 경우 메서드 호출 전에 적용
@Before("cut()")
public void beforeParameterLog(JoinPoint joinPoint) {
// 메서드 정보 받아오기
Method method = getMethod(joinPoint);
log.info("======= AOP Before =======");
log.info("======= method name = {} =======", method.getName());
// 파라미터 받아오기
Object[] args = joinPoint.getArgs();
System.out.println(args.length);
if (args.length <= 0) log.info("no parameter");
else {
for (Object arg : args) {
if(arg != null) {
log.info("parameter type = {}", arg.getClass());
log.info("parameter value = {}", arg);
}
}
}
log.info("======= AOP Before END=======");
}
// Poincut에 의해 필터링된 경로로 들어오는 경우 메서드 리턴 후에 적용
@AfterReturning(value = "cut()", returning = "returnObj")
public void afterReturnLog(JoinPoint joinPoint, Object returnObj) {
// 메서드 정보 받아오기
Method method = getMethod(joinPoint);
log.info("======= AOP After =======");
log.info("======= method name = {} =======", method.getName());
// log.info("return type = {}", returnObj.getClass().getSimpleName());
log.info("return value = {}", returnObj);
log.info("======= AOP After END =======");
}
// JoinPoint로 메서드 정보 가져오기
private Method getMethod(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
return signature.getMethod();
}
}

순서대로 우선 filter -> interceptor pre handle -> aop before -> method -> aop after -> interceptor post handle
이 실행 되는 모습을 확인 할 수 있다.
'Spring Boot' 카테고리의 다른 글
| @Transactional 과 영속성 (0) | 2024.08.02 |
|---|---|
| Lazy Loading (0) | 2024.07.31 |
| 여러 데이터 베이스 사용 시 Transaction (0) | 2024.07.10 |
| R2DBC (0) | 2024.06.17 |
| Spring WebFlux (0) | 2024.03.18 |