AOP๋?
Aspect Oriented Programming์ ์ฝ์๋ก ๊ด์ ์งํฅ ํ๋ก๊ทธ๋๋ฐ์ด๋ค
๋ก์ง์ ํต์ฌ ๊ธฐ๋ฅ๊ณผ ๋ถ๊ฐ ๊ธฐ๋ฅ์ ๊ด์ ์ผ๋ก ๋๋์ด์ ๋ณด๊ณ ๊ฐ๊ฐ์ ๋ชจ๋ํ ํ๋๊ฒ์ด AOP์ ํต์ฌ์ด๋ค
์ผํ๋ชฐ๋ก ์๋ฅผ ๋ค๋ฉด ์ํ์ ๊ฒ์ํ๊ณ , ์ฅ๋ฐ๊ตฌ๋์ ๋ด๊ณ , ๊ฒฐ์ ํ๋ ๋ถ๋ถ์ ํต์ฌ์ ์ธ ๋น์ฆ๋์ค ๋ก์ง์ด๋ผ๊ณ ๋ณผ ์ ์๊ณ , ์ ์ ๋ณ๋ก ํํ์ด์ง์ ์ฒด๋ฅํ๋ ์๊ฐ์ ์ธก์ ํ๋ ๋ถ๋ถ์ ๋ถ๊ฐ ๊ธฐ๋ฅ์ ํด๋นํ๋ค.
AOP๋ ๋ถ๊ฐ๊ธฐ๋ฅ์ Aspect๋ก ์ ์ํ์ฌ ํต์ฌ ๊ธฐ๋ฅ์์ ๋ถ๊ฐ๊ธฐ๋ฅ์ ๋ถ๋ฆฌํ๋ค.
AOP ์ฃผ์ ๊ฐ๋
-
Join point : Aspect๊ฐ ์ ์ฉ๋ ์ ์๋ ์์
- @Around : ํต์ฌ๊ธฐ๋ฅ ์ํ ์ ๊ณผ ํ์ ์ด๋๋ฐ์ด์ค ๊ธฐ๋ฅ ์ํ
- @Before : ํต์ฌ๊ธฐ๋ฅ ํธ์ถ ์ ์ ์ํ
- @After : ํต์ฌ๊ธฐ๋ฅ ์ํ ์ฑ๊ณต/์คํจ ์ฌ๋ถ์ ์๊ด์์ด ์ธ์ ๋ ๋์
- @AfterReturning : ํต์ฌ๊ธฐ๋ฅ ํธ์ถ ์ฑ๊ณต ์ ์ํ
- @AfterThrowing : ํต์ฌ๊ธฐ๋ฅ ํธ์ถ ์คํจ ์ ์ํ
-
Advice : Aspect์ ๊ธฐ๋ฅ์ ์ ์ํ ๊ฒ
-
Point cut : Advice๋ฅผ ์ ์ฉํ ๋ฉ์๋ ๋ฒ์ ์ง์
@Slf4j(topic = "UseTimeAop")
@Aspect
@Component
@RequiredArgsConstructor
public class UserTimeAop {
private final ApiUseTimeRepository apiUseTimeRepository;
@Pointcut("execution(* com.sparta.myselectshop.controller.ProductController.*(..))")
private void product() {
}
@Pointcut("execution(* com.sparta.myselectshop.controller.FolderController.*(..))")
private void folder() {
}
@Pointcut("execution(* com.sparta.myselectshop.naver.controller.NaverApiController.*(..))")
private void naver() {
}
@Around("product() || folder() || naver()") // ๋ฉ์๋ ์คํ ์ ํ์ ์ ์ฉํ ๋ด์ฉ
public Object execute(ProceedingJoinPoint joinPoint) throws Throwable {
// ์ธก์ ์์ ์๊ฐ
long startTime = System.currentTimeMillis();
try {
// ํต์ฌ๊ธฐ๋ฅ ์คํ
Object output = joinPoint.proceed();
return output;
} finally {
// ์ธก์ ์ข
๋ฃ ์๊ฐ
long endTime = System.currentTimeMillis();
long runTime = endTime - startTime;
// ์ฌ์ฉ์ ์ ๋ณด ๊ฐ์ ธ์ค๊ธฐ
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if(auth!=null && auth.getPrincipal().getClass() == UserDetailsImpl.class) {
UserDetailsImpl userDetails = (UserDetailsImpl) auth.getPrincipal();
User loginUser = userDetails.getUser();
ApiUseTime apiUseTime = apiUseTimeRepository.findByUser(loginUser).orElse(null);
if(apiUseTime == null) {
apiUseTime = new ApiUseTime(loginUser, runTime);
} else {
apiUseTime.addUseTime(runTime);
}
apiUseTimeRepository.save(apiUseTime);
}
}
}
}
Spring์์์ AOP
์คํ๋ง AOP๋ ํ๋ก์ ๊ธฐ๋ฐ์ AOP ๊ตฌํ์ฒด์ด๋ค.
์คํ๋ง์ด ํ๋ก์ ๊ฐ์ฒด๋ฅผ ์ค๊ฐ์ ์ฝ์ ํ์ฌ ๋์ํ๋ ํํ์ด๋ค.