Finding Resources with PathMatchingResourcePatternResolver and URLClassloader in JARs

巧了我就是萌 提交于 2019-12-17 18:22:56

问题


I am trying to load all resources with a specific file-extension which are loaded dynamically at runtime using a URLClassloader.

Unfortunately the PathMatchingResourcePatternResolver return no Resources when I use the pattern classpath*:/*.myextension. When I specify a file with its complete name like classpath*:/test.myextension the resource gets loaded, so I think the Classloader is configured right.

URLClassloader classloader = new URLClassloader(jarURLs); // jarURLs look like "file:C:/Temp/test.jar"
Thread.getCurrentThread().setContextClassloader(classloader)
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(classloader);
Resource[] resources = resolver.getResources("classpath*:/*.myextension") // yields empty array
....

How can I do this? I have to load the jars dynamically and I dont know the resource-names in advance.


回答1:


Loading the files dynamically in Spring is simple, I'd change the approach to finding the files with extensions.

Try the following:

ClassLoader cl = this.getClass().getClassLoader(); 
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
Resource[] resources = resolver.getResources("classpath*:/*.xml") ;
for (Resource resource: resources){
    logger.info(resource.getFilename());
}



回答2:


As Tech Trip mentioned in the comment to his answer, I had an error in my pattern. The Spring-documentation is also quiet clear about that (see Warning): "classpath*:" when combined with Ant-style patterns will only work reliably with at least one root directory before the pattern starts...originates from a limitation in the JDK's ClassLoader.getResources()

So I changed my pattern to

classpath*/model/*.myextension

Since the JARs are created from an xText-DSL I have to enforce a convention that the model-folder has to be used.



来源:https://stackoverflow.com/questions/25405167/finding-resources-with-pathmatchingresourcepatternresolver-and-urlclassloader-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!