2022-07-27 TIL
๊น์ํ๋ ์คํ๋ง ๊ณ ๊ธํธ ๊ฐ์๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ์ ๋ฆฌํ ๋ด์ฉ์ ๋๋ค.
AOP(Aspect Oriented Programming) ์ฉ์ด ์ ๋ฆฌ
- Join Point
- Advice๊ฐ ์ ์ฉ๋ ์ ์๋ ์์น, ๋ฉ์๋ ์คํ, ์์ฑ์ ํธ์ถ, ํ๋ ๊ฐ ์ ๊ทผ, static ๋ฉ์๋ ์ ๊ทผ ๊ฐ์ ํ๋ก๊ทธ๋จ ์คํ ์ค ์ง์
- Joint Point๋ ์ถ์์ ์ธ ๊ฐ๋ . AOP๋ฅผ ์ ์ฉํ ์ ์๋ ๋ชจ๋ ์ง์ ์ด๋ผ ์๊ฐํ๋ฉด ๋๋ค.
- Spring AOP๋ ํ๋ก์ ๋ฐฉ์์ ์ฌ์ฉํ๋ฏ๋ก Join Point๋ ์์ ๋ฉ์๋ ์คํ ์ง์ ์ผ๋ก ์ ํ๋๋ค.
- Pointcut
- Join Point ์ค์ Advice๊ฐ ์ ์ฉ๋ ์์น๋ฅผ ์ ๋ณํ๋ ๊ธฐ๋ฅ
- ์ฃผ๋ก AspectJ ํํ์์ ์ฌ์ฉํด์ ์ง์
- ํ๋ก์๋ฅผ ์ฌ์ฉํ๋ Spring AOP๋ ๋ฉ์๋ ์คํ ์ง์ ๋ง Pointcur์ผ๋ก ์ ๋ณ ๊ฐ๋ฅ.
- Target
- Advice๋ฅผ ๋ฐ๋ ๊ฐ์ฒด, ์ฆ Advice(๋ถ๊ฐ ๊ธฐ๋ฅ ๋ก์ง)๋ฅผ ์ ์ฉ๋ฐ๋ ๊ฐ์ฒด. Pointcut์ผ๋ก ๊ฒฐ์
- Advice
- ๋ถ๊ฐ ๊ธฐ๋ฅ
- ํน์ Join Point์์ Aspect์ ์ํด ์ทจํด์ง๋ ์กฐ์น (e.g. ๋ก๊ทธ ๋จ๊ธฐ๊ธฐ, ๋ฉ์๋ ์คํ ์๊ฐ ์ถ๊ฐ)
- Around(์ฃผ๋ณ), Before(์ ), After(ํ)์ ๊ฐ์ ๋ค์ํ ์ข ๋ฅ์ Advice๊ฐ ์์.
- Aspect
๊ป ์กด์ฌ
- Advisor
- ํ๋์ Advice์ ํ๋์ PointCut์ผ๋ก ๊ตฌ์ฑ๋ ํน๋ณํ Advisor
- Spring AOP์์๋ง ์ฌ์ฉ๋๋ ํน๋ณํ ์ฉ์ด
- Weaving
- Pointcut์ผ๋ก ๊ฒฐ์ ํ Target์ Join Point์ Advice๋ฅผ ์ ์ฉ
- Weaving์ ํตํด ํต์ฌ ๊ธฐ๋ฅ ์ฝ๋์ ์ํฅ์ ์ฃผ์ง ์๊ณ ๋ถ๊ฐ ๊ธฐ๋ฅ ์ถ๊ฐํ ์ ์์
- AOP ์ ์ฉ์ ์ํด Aspect๋ฅผ ๊ฐ์ฒด์ ์ฐ๊ฒฐํ ์ํ
- Compile Time(AspectJ compiler)
- Load Time
- Run Time, Spring AOP, Proxy ๋ฐฉ์
Advice ์ข ๋ฅ
@Around
: ๋ฉ์๋ ํธ์ถ ์ ํ์ ์ํ, ๊ฐ์ฅ ๊ฐ๋ ฅํ ์ด๋๋ฐ์ด์ค, ์กฐ์ธ ํฌ์ธํธ ์คํ ์ฌ๋ถ ์ ํ, ๋ฐํ ๊ฐ ๋ณํ, ์์ธ ๋ณํ ๋ฑ์ด ๊ฐ๋ฅ@Before
: ์กฐ์ธ ํฌ์ธํธ ์คํ ์ด์ ์ ์คํ@AfterReturning
: ์กฐ์ธ ํฌ์ธํธ๊ฐ ์ ์ ์๋ฃํ ์คํ@AfterThrowing
: ๋ฉ์๋๊ฐ ์์ธ๋ฅผ ๋์ง๋ ๊ฒฝ์ฐ ์คํ@After
: ์กฐ์ธ ํฌ์ธํธ๊ฐ ์ ์ ๋๋ ์์ธ์ ๊ด๊ณ์์ด ์คํ(finally)
@Slf4j
@Aspect
public class AspectV6Advice {
@Around("hello.aop.order.aop.Pointcuts.orderAndService()")
public Object doTransaction(ProceedingJoinPoint joinPoint) throws Throwable {
try {
//@Before
log.info("[around][ํธ๋์ญ์
์์] {}", joinPoint.getSignature());
Object result = joinPoint.proceed();
//@AfterReturning
log.info("[around][ํธ๋์ญ์
์ปค๋ฐ] {}", joinPoint.getSignature());\
return result;
} catch (Exception e) {
//@AfterThrowing
log.info("[around][ํธ๋์ญ์
๋กค๋ฐฑ] {}", joinPoint.getSignature());
throw e;
} finally {
//@After
log.info("[around][๋ฆฌ์์ค ๋ฆด๋ฆฌ์ฆ] {}", joinPoint.getSignature());
}
}
@Before("hello.aop.order.aop.Pointcuts.orderAndService()")
public void doBefore(JoinPoint joinPoint) {
log.info("[before] {}", joinPoint.getSignature());
}
@AfterReturning(value = "hello.aop.order.aop.Pointcuts.orderAndService()",
returning = "result")
public void doReturn(JoinPoint joinPoint, Object result) {
log.info("[return] {} return={}", joinPoint.getSignature(), result);
}
@AfterThrowing(value = "hello.aop.order.aop.Pointcuts.orderAndService()",
throwing = "ex")
public void doThrowing(JoinPoint joinPoint, Exception ex) {
log.info("[ex] {} message={}", joinPoint.getSignature(),
ex.getMessage());
}
@After(value = "hello.aop.order.aop.Pointcuts.orderAndService()")
public void doAfter(JoinPoint joinPoint) {
log.info("[after] {}", joinPoint.getSignature());
}
}
๋๊ธ๋จ๊ธฐ๊ธฐ