[英]Spring: Request load properties in maven plugin project but use file from project the plugin is used in
我已经编写了使用Spring上下文依赖注入的Maven插件。
在某个时间点,spring必须使用属性文件初始化其中一个bean。 在测试中,一切正常。 但是,当在构建过程中构建插件并在其他项目中使用插件时,将抛出FileNotFoundException。
使用以下命令打印当前的类路径条目时:
ClassLoader cl = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader)cl).getURLs();
for(URL url: urls){
System.out.println("CLASSPATH: " + url.getFile());
}
我唯一得到的是:
CLASSPATH: /path/to/mavendir/boot/plexus-classworlds-2.5.2.jar
通常,通过以下代码加载属性:
Resource resource = springContext.getResource("classpath:/myPluginConfig.properties");
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
但是找不到文件。
我在使用我的插件的项目/ src / main / resources /中放置了正确命名的文件“ myPluginConfig.properties ”。
在过程资源阶段,文件被复制到目标/类目录(我检查了它的存在)。 因此该文件在那里,但类路径以某种方式损坏。
我的插件仅作为快照安装在本地,因此我可以快速更新并重新安装。
谁能帮我解决这个问题?
当我们在不同的项目中使用jar时,资源路径应如下所示:classpath *:myPluginConfig.properties
我的问题的答案是:
在mojo执行期间,这应该称为我的maven。 最好是尽早。
private void enhanceClassloaderAndInitSpring() {
try {
Set<URL> urls = new HashSet<>();
List<Stream<String>> streams = new ArrayList<>();
streams.add(project.getRuntimeClasspathElements().stream());
streams.add(project.getCompileClasspathElements().stream());
streams.add(project.getSystemClasspathElements().stream());
for (String element : streams.stream().flatMap(s -> s).collect(Collectors.toList())) {
System.out.println("Adding element to classpath: " + element);
urls.add(new File(element).toURI().toURL());
}
ClassLoader contextClassLoader = URLClassLoader.newInstance(
urls.toArray(new URL[0]),
Thread.currentThread().getContextClassLoader());
Thread.currentThread().setContextClassLoader(contextClassLoader);
// springContext is just local field in class
springContext = initSpringContext();
} catch (DependencyResolutionRequiredException e) {
throw new RuntimeException(e);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
使用java类加载器或spring上下文获取资源,但不要在资源字符串前加上“ classpath:”前缀(至少在我看来这是行不通的)
Resource resource = springContext.getResource("myPluginConfig.properties"); if (!resource.exists()) { throw new RuntimeException("Resource does not exist and resource object pointing to nothing was created"); } Properties properties = PropertiesLoaderUtils.loadProperties(resource);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.