spring 在 JAR 中使用 PathMatchingResourcePatternResolver 和 URLClassloader 查找资源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25405167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding Resources with PathMatchingResourcePatternResolver and URLClassloader in JARs
提问by lostiniceland
I am trying to load all resources with a specific file-extension which are loaded dynamically at runtime using a URLClassloader.
我正在尝试使用特定文件扩展名加载所有资源,这些资源在运行时使用 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.myextensionthe resource gets loaded, so I think the Classloader is configured right.
不幸的是,当我使用模式时,PathMatchingResourcePatternResolver 没有返回资源classpath*:/*.myextension。当我指定一个具有完整名称的文件时,如classpath*:/test.myextension资源被加载,所以我认为类加载器配置正确。
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.
我怎样才能做到这一点?我必须动态加载 jars 并且我不知道资源名称。
采纳答案by lostiniceland
As Tech Trip mentioned in the comment to his answer, I had an error in my pattern. The Spring-documentationis 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()
正如 Tech Trip 在对他的回答的评论中提到的那样,我的模式有误。在Spring的文档也安静明确有关(见警告)“的classpath *:”在与Ant风格的图案相结合,将仅模式开始前至少有一个根目录下可靠地工作......问题源自限制JDK 的 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.
由于 JAR 是从 xText-DSL 创建的,因此我必须强制执行必须使用模型文件夹的约定。
回答by TechTrip
Loading the files dynamically in Spring is simple, I'd change the approach to finding the files with extensions.
在 Spring 中动态加载文件很简单,我会改变查找带有扩展名的文件的方法。
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());
}

