Search
Duplicate
๐ŸŒฑ

AOP์™€ Proxy

Advisor = @Aspect = Advice + PointCut

JDK Dynamic Proxy

โ€ข
Proxy ๊ฐ์ฒด - Invocation Handler ๋ฅผ ๋ณ€์ˆ˜๋กœ ๊ฐ€์ง„๋‹ค
โ€ข
reflection ์„ ์ด์šฉ
โ€ข
์บ์ŠคํŒ…๋œ ๊ฐ์ฒด์— ๋ฉ”์„œ๋“œ๋ฅผ ์‹คํ–‰ํ•˜๋ฉด Proxy ์˜ invoke ๊ฐ€ ๋จผ์ € ๋ฐ˜์‘(Proxy -1 ํ–‰ ์‹คํ–‰)

๋ฌธ์ œ์ 

โ€ข
interface ๊ฐ€ ๋ฐ˜๋“œ์‹œ ์กด์žฌํ•ด์•ผํ•œ๋‹ค
โ—ฆ
์–ด๋– ํ•œ ์‹œ์ ์—์„œ ๋ฐ˜๋“œ์‹œ interface ๋กœ์„œ ํ˜ธ์ถœ๋˜์–ด์•ผ ํ•œ๋‹ค.
โ€ข
reflection ์ด๋ผ์„œ ๋ฌด๊ฒ๋‹ค.
โ€ข
invoke ๋ฉ”์„œ๋“œ๊ฐ€ ์ƒ๋‹นํžˆ ์ œํ•œ์ ์ด๋‹ค.

CGLIB

โ€ข
ProxyFactoryBean vs Enhancer
โ—ฆ
EnhancerBySpringCGLIB vs EnhancerByCGLIB
โ—ฆ
implements ํ•˜๋Š” MethodInterceptor ๊ฐ€ ๋‹ค๋ฅด๋‹ค
โ–ช
org.aopalliance.intercept.MethodInterceptor;
โ–ช
org.springframework.cglib.proxy;
โ—ฆ
@Transactional ์˜ ํ”„๋ก์‹œ๋“ค์€ ๋Œ€๋ถ€๋ถ„ EnhancerBySpringCGLIB or Dynamic Proxy(interface ๊ฐ€ ์žˆ๋Š” ์• ๋“ค) ์ด๋‹ค.

ProxyFactoryBean

โ€ข
Aop ๊ฐ€ ๊ฑธ๋ฆฐ Bean์„ ๋“ฑ๋กํ•  ๋•Œ ๋“ฑ๋ก๋œ๋‹ค.
โ€ข
ํ•ด๋‹น ๊ฐ์ฒด์˜ ๋ฉ”์„œ๋“œ๊ฐ€ ํ˜ธ์ถœ๋  ๋•Œ CGLIB ๊ฐ์ฒด์˜ ๋ฉ”์„œ๋“œ๊ฐ€ ํ˜ธ์ถœ๋˜๊ณ (-1ํ–‰)
โ€ข
DynamicAdvisedInterceptor ๊ฐ€ ๋™์ž‘ํ•œ๋‹ค. ์–˜๊ฐ€ ๋“ฑ๋ก๋œ advisor ๋“ค ์‹คํ–‰์‹œํ‚จ๋‹ค.
โ€ข
advisor ๋ฅผ ๊ฐ•์ œํ•˜๋Š” ๊ฒƒ ๊ฐ™๋‹ค โ†’ ์ด๋Š” ์ถ”ํ›„์— ์ฐจ์ฐจ ์•Œ์•„๋ณด์ž!

AspectJ

โ€ข
implementation group: 'org.springframework', name: 'spring-aop', version: '5.2.22.RELEASE'
โ€ข
์•ˆํ†ตํ•จ
โ€ข
Bean named 'userService' is expected to be of type 'aop.stage2.UserService' but was actually of type 'com.sun.proxy.$Proxy71โ€™
์ด ์—๋Ÿฌ ๊ณ„์† ๋‚จ
โ€ข
UserService ๋Š” @Component ๋ถ™์ธ ํด๋ž˜์Šค
โ€ข
aop ๊ด€๋ จ implementation ํ•จ
โ€ข
โ€ข
Component ๋Š” EnhancerBySpringCglib ์ด๋‹ค.
AspectJ: AOP ๊ธฐ์ˆ ์˜ ์›์กฐ, ๊ฐ€์žฅ ๊ฐ•๋ ฅํ•œ AOP ํ”„๋ ˆ์ž„์›Œํฌ
AspectJ ์ž์ฒด๋Š” Proxy ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค.
์Šคํ”„๋ง๋„ AspectJ ์˜ ํฌ์ธํŠธ์ปท ํ‘œํ˜„์‹์„ ์ฐจ์šฉํ•ด์„œ ์‚ฌ์šฉ
ํ”„๋ก์‹œ ๋ฐฉ์‹๋ณด๋‹ค ๊ฐ•๋ ฅํ•˜๊ณ  ์œ ์—ฐํ•œ AOP ๊ฐ€ ๊ฐ€๋Šฅ
โ€ข
์˜ค๋ธŒ์ ํŠธ ์ƒ์„ฑ, ํ•„๋“œ ๊ฐ’์˜ ์กฐํšŒ์™€ ์กฐ์ž‘, ์Šคํƒœํ‹ฑ ์ดˆ๊ธฐํ™” ๋“ฑ ๋‹ค์–‘ํ•œ ์ž‘์—…์— ๋ถ€๊ฐ€ ๊ธฐ๋Šฅ์„ ๋ถ€์—ฌ
Service ๋Š” CGLIB, Repository ๋Š” JDK Dynamic Proxy!
์ด์œ ๋Š” Proxy ์ƒ์„ฑ์‹œ if ์ ˆ์— interface ๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธํ•จ. ์žˆ์œผ๋ฉด JDK Dynamic Proxy ๋กœ ์ƒ์„ฑํ•ด๋ฒ„๋ฆผ
๊ทผ๋ฐ JDK Dynamic Proxy ์ด๋‹ค. ๊ทธ๋ž˜์„œ ์–˜๋„ invoke handler ๊ฐ€ ์•„๋‹ˆ๊ณ  advisor ๋กœ ๋ˆ๋‹ค.

@Transactional

โ€ข
ProxyFactoryBean ์œผ๋กœ ์ƒ์„ฑ๋œ SpringCGLIB ์„ ์ด์šฉํ•œ๋‹ค
โ€ข
advisor ๋Š” BeanFactoryTransactionAttributeSourceAdvisor
โ—ฆ
advice ๋Š” TransactionInterceptor
โ—ฆ
pointcut ์€ TransactionAttributeSourcePointcut