tomcat中用classloader重新加载配置文件
tomcat中用classloader重新加载配置文件:
tomcat中从current thead中获取的class加载器为tomcat提供的WebappClassLoader,此classloader提供的getResourceAsStream方法会先根据资源路径到其已加载资源中查找,若找到则直接返回。反之则由classloader加载后返回,因此再资源文件更新以后,classloader不能侦测到,返回的输入流对应的资源文件为第一次加载的文件;
稍做改变可避免此问题:
先调用classloader的:public URL getResource(String name)
根据返回的URL再获取输入流,即避免了缓存的问题;
@SuppressWarnings("unchecked")17public Class loadClass(String classPath, String className)18 throws ClassNotFoundException {19 try {20 String url = classPathParser(classPath)21 + classNameParser(className);22 System.out.println(url);23 URL myUrl = new URL(url);24 URLConnection connection = myUrl.openConnection();25 InputStream input = connection.getInputStream();26 ByteArrayOutputStream buffer = new ByteArrayOutputStream();27 int data = input.read();28 while (data != -1) {29 buffer.write(data);30 data = input.read();31 }32 input.close();33 byte[] classData = buffer.toByteArray();34 return defineClass(noSuffix(className), classData, 0,35 classData.length);36 } catch (MalformedURLException e) {37 e.printStackTrace();38 } catch (IOException e) {39 e.printStackTrace();40 }41 return null;42}