개발일기장

Spring Boot - AOP (1) 본문

Spring Boot

Spring Boot - AOP (1)

게슬 2023. 12. 11. 21:05
728x90

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%ED%95%B5%EC%8B%AC-%EC%9B%90%EB%A6%AC-%EA%B3%A0%EA%B8%89%ED%8E%B8/dashboard

 

스프링 핵심 원리 - 고급편 - 인프런 | 강의

스프링의 핵심 원리와 고급 기술들을 깊이있게 학습하고, 스프링을 자신있게 사용할 수 있습니다., 핵심 디자인 패턴, 쓰레드 로컬, 스프링 AOP스프링의 3가지 핵심 고급 개념 이해하기 📢 수강

www.inflearn.com

 

공통 로직 분리를 위해서 사용함..

https://tlqckd0.tistory.com/105

 

Spring Proxy Factory

Java에서 Proxy사용하는 방법에 대해서 두가지 했었음 1. Jdk 동적 Proxy >> Interface가 있어야함. InvocationHandler를 구현해서 객체 생성 후 Proxy를 생성해서 사용 https://tlqckd0.tistory.com/102 Proxy ... Proxy 사용

tlqckd0.tistory.com

Spring boot AOP에서는 proxy방식으로 사용한다 카던데 그래서 사용법도 비스므리함.


1. @Aspect, @Around

implementation 'org.springframework.boot:spring-boot-starter-aop'

요거 추가를 해줘야 한다.

 

@Aspect
@Slf4j
public class A {

    @Around("execution(* {패키지이름}..*(..))")
    public Object method(ProceedingJoinPoint joinPoint) throws  Throwable{
        return joinPoint.proceed();
    }
}

Class에 @Aspect를 붙여주고

method에 @Around를 붙여서 Pointcut을 등록해주고 로직을 구현해주면 된다. 파라미터는 ProceedingJoinPoint

실제 method 실행은 joinPoint.proceed를 호출하면 된다.


2. Pointcut 분리

    @Pointcut("execution({AOP 표현식})")
    private void AA(){};

    @Pointcut("execution({AOP 표현식})")
    private void BB(){};

    @Around("AA()")
    public Object doAA(ProceedingJoinPoint joinPoint) throws  Throwable{
    	// 로직 수행
    }

    @Around("AA() && BB()")
    public Object doBB(ProceedingJoinPoint joinPoint) throws  Throwable{
    	// 로직 수행
    }

이렇게 Pointcut을 분리해서 사용 할 수도 있고  AOP 표현식에서 && (and), ||(or) , ! (not)을 사용해서 조합할 수도 있음.


# Pointcut class 분리

public class PP {

    @Pointcut("execution({AOP 표현식})")
    public void AA(){};

    @Pointcut("execution({AOP 표현식}")
    public void BB(){};

    @Pointcut("AA() && BB()")
    public void AAandBB(){}
}

이렇게 Pointcut을 모아둔 class를 만든 다음에 호출해서 사용할 수도 있다. (method는 public으로 해야함.)

    @Around("패키지.PP.AA")
    public Object doAA(ProceedingJoinPoint joinPoint) throws  Throwable{
		// 로직 수행
    }

    @Around("패키지.PP.AAandBB")
    public Object doAAandBB(ProceedingJoinPoint joinPoint) throws  Throwable{
		// 로직 수행
    }

 


3. AOP 순서 조절 @Order(n)

하나의 class 내부에서는 순서 조절을 할 수 없음..그냥 지맘대로임 그래서 클래스를 분리하면 됨

    @Aspect
    @Order(2)
    public class AA {
        @Around("???")
        public Object doLogicAA(ProceedingJoinPoint joinPoint) throws  Throwable{
			// 로직 수행
        }
    }

    // 순서는 Class 단위로 설정이 가능하다..
    @Aspect
    @Order(1)
    public class BB {
        @Around("???")
        public Object doLogicBB(ProceedingJoinPoint joinPoint) throws  Throwable{
			// 로직 수행
        }
    }

이렇게 하는 경우 AA, BB둘 다 해당하는 method의 경우 실행 시 BB 먼저 실행이 된다..

728x90
Comments