๐ Web/Spring, JPA
[Spring] AOP ์ฌ์ฉ ์์ - AOP class ๊ตฌํ
a n u e
2022. 3. 24. 21:27
AOP๋ IOC, DI, DL๊ณผ ๋๋ถ์ด ์คํ๋ง์ ๋ํ์ ์ธ ํน์ฑ์ด๋ค.
๊ฐ๋จํ๊ฒ ๋งํ์๋ฉด, ๊ณตํต์ ์ธ ์์๋ ๋ฐ๋ณต๋์ด ์ฌ์ฉ๋๋ ์์๋ฅผ ํ ๊ณณ์ ๋ฌถ์ด ๊ด๋ฆฌํ๋ ๊ด์ ์งํฅ์ ํ๋ก๊ทธ๋๋ฐ ๊ธฐ๋ฒ์ด๋ผ ํ ์ ์๋ค.
method๊ฐ ์คํ๋ ๋๋ง๋ค
method์ parameter์ method return value๋ฅผ console์ ์ฐ๋ AOP๋ฅผ ๊ตฌํํด๋ณด์
(๊ธฐ์กด์ ๊ฐ์ธ์ ์ผ๋ก ๊ณต๋ถํ๋ ํ๋ก์ ํธ์ ๋ฃ์ด๋ณด์๋ค)
๊ทธ ์ ์ใ กํด๋น ๊ธฐ๋ฅ์ ๊ตฌํํ๋ ค๋ฉด, AOP ๊ธฐ๋ฅ๊ณผ ๊ด๋ จ๋ ์คํ๋ง annotaion์ ๋ํด ์์์ผํ๋ค.
@Aspect | AOP ํด๋์ค ์ ์ ์ ์ฌ์ฉ |
@Pointcut | AOP ๊ธฐ๋ฅ์ ์ง์ ํ๊ธฐ ์ํ ๋ฒ์๋ฅผ ์ค์ ํ ์ ์๋ค |
@Before | ๋ฉ์๋ ์คํ ์ |
@After | ๋ฉ์๋ ์คํ(์ฑ๊ณต) ํ |
@AfterReturning | ๋ฉ์๋๊ฐ ์ ์ ์ข ๋ฃ ์ |
@AfterThrowing | ๋ฉ์๋์์ ์์ธ ๋ฐ์ ์ |
servlet-context.xml
root-context.xml
ParamAop Class ์์ฑ
package com.shop.controller;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class ParamAop {
//ํด๋น ํจํค์ง ํ์ ํด๋์ค ์ ๋ถ ์ ์ฉ
@Pointcut("execution(* com.shop.controller..*.*(..))")
private void paramCall() {}
/* JoinPoint interface
* ํด๋ผ์ด์ธํธ๊ฐ ํธ์ถํ ๋น์ง๋์ค์ ๋ฉ์๋ ์ ๋ณด๋ฅผ ์๊ธฐ ์ํ ์ธํฐํ์ด์ค
*/
//paramCall method ์คํ ์ ์ ์คํํ๋ method๋ผ๋ ์๋ฏธ
@Before("paramCall()")
public void before(JoinPoint joinPoint)
{
//method ๋งค๊ฐ๋ณ์๋ฅผ ๋ฐฐ์ด์ ๋ด๋๋ค
Object[] args = joinPoint.getArgs();
//๋งค๊ฐ๋ณ์ ๋ฐฐ์ด์ ์ข
๋ฅ ๋ฐ ๊ฐ ์ถ๋ ฅ
for(Object obj : args) {
System.out.println(" ์ปจํธ๋กค๋ฌ ๋งค๊ฐ๋ณ์ ํ์
์ ์๋ ค์ค : " + obj.getClass().getSimpleName());
System.out.println(" ์ปจํธ๋กค๋ฌ ๋งค๊ฐ๋ณ์ ๊ฐ์ ์๋ ค์ค : " + obj);
}
}
//paramCall method๊ฐ ์ข
๋ฃ๋๋ฉด afterReturn method๋ฅผ ์คํ์์ผ์ค
//@AfterReturning ์ด๋
ธํ
์ด์
์ returning ๊ฐ๊ณผ afterReturn ๋งค๊ฐ๋ณ์ obj์ ์ด๋ฆ์ด ๊ฐ์์ผ ํจ
@AfterReturning(value = "paramCall()", returning = "obj")
public void afterReturn(JoinPoint joinPoint, Object obj) {
System.out.println(" ์ปจํธ๋กค๋ฌ์์ Return๋๋ ๊ฐ์ ์๋ ค์ค : " + obj);
}
}
References