맨땅에 헤딩하는 개바른자

[AOP] @annotation 본문

JAVA/AOP

[AOP] @annotation

앵낄낄 2023. 3. 23. 21:02
반응형

AOP에서는 @annotation과 @args를 이용하여 메소드 실행 전/후에 추가적인 작업을 할 수 있습니다.

  • @annotation: 메소드에 적용된 어노테이션을 기반으로 추가 작업을 수행할 수 있습니다. 예를 들어, @Transactional 어노테이션이 적용된 메소드에서는 트랜잭션을 관리하는 작업을 추가로 수행할 수 있습니다.
  • @args: 메소드의 인자에 따라 추가 작업을 수행할 수 있습니다. 예를 들어, 메소드의 인자 중 특정 클래스 타입을 가진 인자가 있는 경우, 그에 맞는 추가 작업을 수행할 수 있습니다.

이러한 어노테이션을 이용하여 AOP에서는 메소드 실행 전/후에 로깅, 보안, 트랜잭션 등 다양한 작업을 추가로 수행할 수 있습니다.

예제코드

어노테이션을 생성

package hello.aop.member.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodAop {
    String value();
}

MemberService의 메소드위에다 @MethodAop를 붙인상태이다.

package hello.aop.pointcut;

import hello.aop.member.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;

@Slf4j
@Import(AtAnnotationTest.AtAnnotationAspect.class)
@SpringBootTest
public class AtAnnotationTest {

    @Autowired
    MemberService memberService;

    @Test
    void success() {
        log.info("memberService Proxy={}", memberService.getClass());
        memberService.hello("helloA");
    }

    @Slf4j
    @Aspect
    static class AtAnnotationAspect {
        @Around("@annotation(hello.aop.member.annotation.MethodAop)")
        public Object doAtAnnotation(ProceedingJoinPoint joinPoint) throws Throwable {
            log.info("[@annotation] {}", joinPoint.getSignature());
            return joinPoint.proceed();
        }
    }
}

위 테스트코드를 실행하면 아래와같이 AOP가 동작한걸 볼 수 있다.

반응형

'JAVA > AOP' 카테고리의 다른 글

[AOP] 실전예제 Service단 파라미터 Null체크 사용기  (1) 2023.04.25
[AOP] 실전예제 로그TRACE  (0) 2023.04.18
[AOP] this, target  (0) 2023.03.29
[AOP] 매개변수 전달  (0) 2023.03.29
[AOP] @target @within  (0) 2023.03.23