AOP란

단비·2023년 5월 19일
0

학습

목록 보기
56/66

AOP (Aspect Oriented Programming)

비지니스 로직 등의 핵심 기능 (Core Concerns)들과 로깅, 보안 , 트랜잭션 처리 등
핵심 기능을 도와주는 부가기능 (Cross-cutting Concerns)으로 분리해서 모듈화 하는 것


Primary Concern (Core Concern)

핵심기능, 비즈니스 로직으로만 구성되어 있음

Cross- Cutting Concern

로깅, 보안 등의 기능을 하는 부가 기능

Point Cut

부가기능을 어디에 적용시키는지

Aspect (Adviser) = Point Cut + Cross-Cutting Concern

Weaving
런타임 때 Aspect(Adviser)를 핵심 기능에 끼워넣는 것





사용 방법

build.gralde

// https://mvnrepository.com/artifact/org.springframework/spring-aop
implementation group: 'org.springframework', name: 'spring-aop', version: '6.0.9'

application 클래스에 어노테이션 추가

@EnableAspectJAutoProxy

Aspect 클래스

  • proceed()는 메소드를 실행하는 메소드
  • execution 설정법
    • * 경로..(..) : 경로의 모든 파일의 모든 메소드
    • * 경로..post(..) : 경로의 모든 파일의 post 메소드
    • * 경로..get(..) : 경로의 모든 파일의 get 메소드
@Aspect
@Component
public class LoggingAspect {
    @Before("execution(* com.test.service.*.get*(..)) ||" +
    	"execution(* com.test.service.*.post*(..))")
    public void loggerBefore(JoinPoint joinPoint) {
        System.out.println("get 또는 post로 시작하는 메서드가 시작됩니다.");
    }
 
    @After("execution(* com.test.service.*.get*(..))")
    public void loggerAfter() {
        System.out.println("get으로 시작하는 메서드가 끝났습니다.");
    }
 
    @Around("execution(* com.test.controller.UserController.*(..))")
    public Object loggerAround(ProceedingJoinPoint pjp) throws Throwable {
        ...
        
        Object result = pjp.proceed(); // 메소드 실행
 
 		...
        
        return result;
    }
}
종류기능
@PointCut타겟을 직접 정의할 수 있음
(value, argNames)
@Before타겟이 실행되기 전 어드바이스 기능 수행
(value, argNames)
@After타겟이 실행된 후 어드바이스 기능 수행 (결과에 상관 x)
return 값을 가져올 수 있음
(value, argNames)
@AfterReturning타겟이 성공적으로 리턴값을 반환한 경우 어드바이스 기능 수행
(value, returning, pointcut, argNames)
@AfterThrowing타멧 메소드 수행 중 예외 발생 시 어드바이스 기능 수행
(value, throwing, pointcut, argNames)
@Around타켓 호출 전 / 후 어드바이스 기능 수행
(value, argNames)

ProceedingJoinPoint의 값

  • getArgs() : 메서드 인수 반환
  • getThis() : 프록시 객체 반환
  • getTarget() : 대상 객체 반환
  • getSignature() : 조언되는 메서드에 대한 설명 반환
  • toString() : 조언되는 방법에 대한 유용한 설명 인쇄





참고사이트

[Spring] Spring AOP 이용하기 - 코딩의 성지

profile
tistory로 이전! https://sweet-rain-kim.tistory.com/

0개의 댓글