SpringBoot Custom Annotation 생성하기 - (2) 메소드에 부여

단비·2023년 5월 23일
0

학습

목록 보기
63/66

이전 포스터 - 필드에 부여하는 방법
AOP 포스터


사용 방법

1. 어노테이션 선언

  • 자세한 설정법은 위 링크 참조
@Inherited
// 메소드에서만 사용 가능
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AccessRole {
    RoleFinal role();
}

2. Aspect 클래스 생성

  • joinPoint.proceed() 명령문 실행 시 타겟메소드가 실행됨
    (만약 response 값으로 dto를 보내고 싶은 경우 return으로 보내면됨)
  • 타겟 설정은 ||(or) 또는 &&(and) 다중 설정 가능함
@Aspect
@Component
public class AccessAspect {
    private static Logger logger = LoggerFactory.getLogger(AccessAspect.class);
    
	@AfterReturning(value = "execution(* com.dbkim.controller.*.*(..)) ||" +
            "execution(* com.dbkim.exceptionHandler.ExceptionHandlers.nullEx(..))",
            returning = "apiDTO")
    public void loggerAfter(ApiDTO apiDTO) throws IOException {
        if(apiDTO.getRtCode() != 0)
            logger.error("HTTP/HTTPS Response : {}", apiDTO);
        else
            logger.info("HTTP/HTTPS Response : {}", apiDTO);
    }
    @Around("@annotation(com.dbkim.annotation.AccessRole)")
    public Object accessRole(ProceedingJoinPoint joinPoint) throws Throwable {
    	...
        return joinPoint.proceed();
    }

AfterReturning에서 @annotation을 통해 타겟 메소드를 지정하는 것이 아닌,
execution로 지정하는 경우 해당 조건에 맞는 메소드들이 정상적인 리턴을 할 경우 AfterReturning 메소드가 실행됨

따라서 어노테이션을 붙이지 않은 error 메소드에도 AfterReturning이 실행됨!!
(return값이 void가 아닌 AfterReturning의 returning 값과 같아야함!)


3. 어노테이션 사용

  • 어노테이션 선언할 때 변수를 선언해줬으니 매개변수 부여 필요
@PostMapping("/sign-up")
@ResponseBody
@AccessRole(role = RoleFinal.NONE)
public ApiDTO signUp(
	@RequestBody UserRequest request
) throws Exception {
	...
}




❗❗ 어노테이션 매개변수 값 가져오는 방법 ❗❗

ProceedingJoinPoint의 getSignature 메소드를 활용하여

어노테이션을 통해 호출된 메소드를 가져온 뒤,
부여된 어노테이션의 고유한 값을 가져옴

@Around("@annotation(com.dbkim.annotation.AccessRole)")
public Object accessRole(ProceedingJoinPoint joinPoint) throws Throwable {
		MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
		RoleFinal role = methodSignature.getMethod().getAnnotation(AccessRole.class).role();





참고사이트

JAVA request, response 클래스/메서드 내에서 생성

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

0개의 댓글