본문 바로가기

공부 기록/Spring

[Spring] AOP의 활용

디펜던시 설정

dependencies {

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

AOP의 활용1

@Aspect
@Component
public class ParameterAop {

    @Pointcut("execution(* com.example.demo.controller..*.*(..))")
    private void cut() {
    
        ...
    
    }

    @Before("cut()")
    public void before(JoinPoint joinPoint) {

        ...
        
    }

    @AfterReturning(value = "cut()", returning = "obj")
    public void afterReturn(JoinPoint joinPoint, Object obj) {

        ...

    }
}

@Aspect  => 해당 클래스는 AOP로 동작
@Component  => 스프링에서 관리되어야 함

@Pointcut("execution(* com.example.demo.controller..*.*(..))") => ~ controller 하위의 메서드를 모두 AOP로 본다.

@Before("cut()") => cut() 메서드 실행 전 동작

@AfterReturning(value = "cut()", returning = "obj") => cut() 메서드 실행 후 동작, obj 값 리턴. returning의 값은 아래 매개변수와 이름이 동일해야 함


커스텀 어노테이션 생성

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Timer {
    
}

  

@Target : 어노테이션을 적용할 수 있는 타입

@Retention : 어노테이션 타입을 언제까지 보유할지 설정

  


AOP의 활용2

@Aspect
@Component
public class TimerAop {

    @Pointcut("execution(* com.example.demo.controller..*.*(..))")
    private void cut(){}

    @Pointcut("@annotation(com.example.demo.annotation.Timer)")
    private void enableTimer(){}
    
    @Around("cut() && enableTimer()")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        
        Object result = joinPoint.proceed();  // 위로는 Before, 아래로는 After
        
        stopWatch.stop();
        System.out.println(stopWatch.getTotalTimeSeconds());
    }
}

  


@Component VS @Bean VS @Configuration

@Component : 클래스 단위 등록

@Bean : 메서드 단위 등록

@Configuration : 하나의 클래스에 여러 개의 Bean 등록 가능

'공부 기록 > Spring' 카테고리의 다른 글

[Spring] Exception Handling  (0) 2023.05.04
[Spring] Validation(2) - Custom Validation  (0) 2023.05.01
[Spring] Validation(1) - Annotation  (0) 2023.05.01
[Spring] AOP  (0) 2023.03.28
[Spring] IoC(Inversion of Control, 제어의 역전), DI  (0) 2023.03.23