您好,登录后才能下订单哦!
这篇文章主要讲解了“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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。