您好,登錄后才能下訂單哦!
這篇文章主要講解了“SpringFramework中ProxyFactory的用法”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“SpringFramework中ProxyFactory的用法”吧!
Spring版本是5.0.4.release.
ProxyFactory在Springaop中占有舉足輕重的地位,用來間接創建代理,如下List-1所示,我們給ServiceImpl創建代理。
List-1
public interface IService { String hello(); } public class ServiceImpl implements IService { @Override public String hello() { System.out.println("service的hello方法"); return "Hello"; } } import org.springframework.aop.MethodBeforeAdvice; import java.lang.reflect.Method; public class BeforeAdvice implements MethodBeforeAdvice { @Override public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println("beforeAdvice的before方法"); } } import org.springframework.aop.AfterReturningAdvice; import java.lang.reflect.Method; public class AfterAdvice implements AfterReturningAdvice { @Override public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { System.out.println("AfterAdvice的afterReturning方法"); } } import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; public class AopTest { @Test public void test(){ ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setInterfaces(IService.class); proxyFactory.setTarget(new ServiceImpl()); proxyFactory.addAdvice(new BeforeAdvice()); proxyFactory.addAdvice(new AfterAdvice()); IService proxy = (IService) proxyFactory.getProxy(); String result = proxy.hello(); System.out.println(result); } }
運行結果如下List-2
List-2
beforeAdvice的before方法 service的hello方法 AfterAdvice的afterReturning方法 Hello
proxyFactory.addAdvice(new BeforeAdvice())時,會將Advice轉換為Advisor,最后再調用addAdvisor方法。
當我們調用ProxyFactory的getProxy時,會先調用createAopProxy()->getAopProxyFactory().createAopProxy(this),AopProxyFactory是DefaultAopProxyFactory——在另一篇里面講到。createAopProxy方法里面把this傳入,ProxyFactory實現了AdvisedSupport,所以在createAopProxy時將ProxyFactory中設置的targetSource、advice等傳遞到了DefaultAopProxyFactory,之后傳遞到JdkDynamicAopProxy中。
最后getProxy調用的是JdkDynamicAopProxy的getProxy方法,如下List-3所示,Proxy.newProxyInstance的方法中,最后的InvocationHandler是this——JdkDynamicAopProxy實現了InvocationHandler,所以當我們調用目標類的方法時,會調用JdkDynamicAopProxy的invoke方法。
List-3
public Object getProxy(@Nullable ClassLoader classLoader) { if (logger.isDebugEnabled()) { logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource()); } Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true); findDefinedEqualsAndHashCodeMethods(proxiedInterfaces); return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this); }
這里就引出了一個問題,在JdkDynamicAopProxy的invoke方法中,攔截器鏈是怎么構造出來了。
感謝各位的閱讀,以上就是“SpringFramework中ProxyFactory的用法”的內容了,經過本文的學習后,相信大家對SpringFramework中ProxyFactory的用法這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。