본문 바로가기
Kotlin

[Spring Boot] AOP 적용하기

by 빨간맛캔디 2022. 11. 1.

Gradle dependency 추가

implementation("org.springframework.boot:spring-boot-starter-aop")

 

AOP를 활성하는 어노테이션 추가 Application  클래스에  추가해준다

@EnableAspectJAutoProxy
@SpringBootApplication(exclude = [SecurityAutoConfiguration::class])
class Application

fun main(args: Array<String>) {
    runApplication<Application>(*args)
}

 

AOP를 처리하기 위한 어노테이션 

import java.lang.annotation.ElementType
import java.lang.annotation.RetentionPolicy

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class Auth

 

공통 로직 Aspect

@Aspect
@Component
class AuthAspect(private val memberService: MemberService,
                 private val httpServletRequest: HttpServletRequest){

    @Around("@annotation(Auth)")
    @Throws(Throwable::class)
    fun accessToken(joinPoint: ProceedingJoinPoint):Any{
        val accessToken = httpServletRequest.getHeader(AUTHORIZATION_HEADER)
        val token = accessToken.substring(BEARER_PREFIX.length)
        memberService.checkToken(token) //토큰 검증 service를 따로 구현 해야함
        var proceed = joinPoint.proceed()
        return proceed
    }
    companion object {
        const val AUTHORIZATION_HEADER = "Authorization"
        const val BEARER_PREFIX = "Bearer "
    }

}

 

API에 적용하기

AOP를 적용할 API에 만든 @Auth 어노테이션을 추가해준다

 

반응형

댓글