本文主要研究一下dubbo的ClassLoaderFilter
dubbo-2.7.2/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ClassLoaderFilter.java
@Activate(group = CommonConstants.PROVIDER, order = -30000) public class ClassLoaderFilter implements Filter { @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { ClassLoader ocl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(invoker.getInterface().getClassLoader()); try { return invoker.invoke(invocation); } finally { Thread.currentThread().setContextClassLoader(ocl); } } }
dubbo-2.7.2/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ClassLoaderFilterTest.java
public class ClassLoaderFilterTest { private ClassLoaderFilter classLoaderFilter = new ClassLoaderFilter(); @Test public void testInvoke() throws Exception { URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1"); String path = DemoService.class.getResource("/").getPath(); final URLClassLoader cl = new URLClassLoader(new java.net.URL[]{new java.net.URL("file:" + path)}) { @Override public Class<?> loadClass(String name) throws ClassNotFoundException { try { return findClass(name); } catch (ClassNotFoundException e) { return super.loadClass(name); } } }; final Class<?> clazz = cl.loadClass(DemoService.class.getCanonicalName()); Invoker invoker = new MyInvoker(url) { @Override public Class getInterface() { return clazz; } @Override public Result invoke(Invocation invocation) throws RpcException { Assertions.assertEquals(cl, Thread.currentThread().getContextClassLoader()); return null; } }; Invocation invocation = Mockito.mock(Invocation.class); classLoaderFilter.invoke(invoker, invocation); } }
ClassLoaderFilter实现了Filter接口,其invoke方法首先获取当前线程的contextClassLoader,然后将其ContextClassLoader设置为invoker.getInterface().getClassLoader(),之后执行invoker.invoke方法,最后将当前线程的classLoader重置为原来的contextClassLoader