프로그래밍 노트/SPRING

[Spring] AOP_3 : @AOP

깡냉쓰 2020. 4. 6. 00:06
728x90
반응형

애노테이션 기반의 스프링 @AOP

의존성 추가

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

애스팩트 정의

  • @Aspect
  • 빈으로 등록해야 하니까(컴포넌트 스캔을 사용한다면) @Component도 추가.

포인트컷 정의

  • @Pointcut(표현식)
  • 주요 표현식
    • execution
    • @annotation
    • bean
  • 포인트컷 조합
    • &&, ||, !
@Aspect
@Component
public class PerfAspect {
    // Advice + Pointcut
    @Around("execution(* com.corn..*.EventService.*(..))")
    public Object logPerf(ProceedingJoinPoint pjp) throws Throwable {
        long begin = System.currentTimeMillis();
        Object retVal = pjp.proceed();
        System.out.println(System.currentTimeMillis() - begin);
        return retVal;
    }
}

Annotation을 만들어서 사용하는 것이 깔끔함

@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
@Documented
public @interface PerfLogging {

}
@Service
public class SimpleEventService implements EventService{
    @Override
    @PerfLogging
    public void createEvent() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Created an event");
    }

    @Override
    public void publishEvent() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Published on event");
    }
}
@Aspect
@Component
public class PerfAspect {
    // Advice + Pointcut
    @Around("@annotation(PerfLogging)")
    public Object logPerf(ProceedingJoinPoint pjp) throws Throwable {
        long begin = System.currentTimeMillis();
        Object retVal = pjp.proceed();
        System.out.println(System.currentTimeMillis() - begin);
        return retVal;
    }
}

어드바이스 정의

  • @Before
  • @AfterReturning
  • @AfterThrowing
  • @Around

참고

https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop-pointcuts

출처 : 백기선님의 스프링 프레임워크 핵심 기술 강좌

728x90
반응형