“它在 eclipse 中工作正常,但是当我创建 jar 并运行时它会给我这个异常。这是我正在使用的非 Web spring 引导应用程序,我应该作为独立的 jar 运行”
java.lang.IllegalArgumentException: name
at sun.misc.URLClassPath$Loader.findResource(Unknown Source) ~[na:1.8.0_171]
at sun.misc.URLClassPath.findResource(Unknown Source) ~[na:1.8.0_171]
at java.net.URLClassLoader$2.run(Unknown Source) ~[na:1.8.0_171]
at java.net.URLClassLoader$2.run(Unknown Source) ~[na:1.8.0_171]
at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_171]
at java.net.URLClassLoader.findResource(Unknown Source) ~[na:1.8.0_171]
at org.springframework.boot.loader.LaunchedURLClassLoader.findResource(LaunchedURLClassLoader.java:58) ~[extension-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at java.lang.ClassLoader.getResource(Unknown Source) ~[na:1.8.0_171]
at java.net.URLClassLoader.getResourceAsStream(Unknown Source) ~[na:1.8.0_171]
最佳答案
可能有点晚了,但我最近在 Windows 上遇到了同样的错误,并用一个肮脏的 hack 修复了它。我希望 future 寻找相同问题的人会发现这对他们的问题有用。
首先,eclipse 以不同的方式“运行”您的 Spring Boot 应用程序。它不执行 java -jar foo.jar
而是直接引用所有类和库,即 java -classpath xxx/target/classes:a.jar:b.jar...
。所以有时在 eclipse 中运行的行为会有所不同。
我想你遇到了和我一样的情况,你有一个 Spring Boot 应用程序,你想将它打包为可执行的 jar 并且你正在引用外部依赖项并且无法修复这些外部依赖项中的错误。
我发现我正在使用的外部库中的某处正在生成一个临时文件并使用 Java 的 ClassLoader
读取它,但是 Spring Boot 的 LaunchedURLClassLoader
无法处理 Windows 的"x:\"语法
就我而言,是
URL findResource(name): C:\foo\bar.xml
所以 hack 是构建您自己的 LaunchedURLClassLoader
并将其替换为可执行 jar。如果解压可执行 jar,您将在 org\springframework\boot\loader
下找到 LaunchedURLClassLoader.class
。这个想法是将 C:\foo\bar.xml
重新写入 file:///C:/foo/bar.xml
这样 Java ClassLoader 就会知道如何处理文件。
...
package org.springframework.boot.loader;
...
public class LaunchedURLClassLoader extends URLClassLoader {
...
@Override
public URL findResource(String name) {
// This is where I added the dirty hack
if (name.contains(":\\") && !name.startsWith("file:///")) {
System.out.println("URL findResource(name): " + name); // just for you to debug
name = "file:///" + name.replace("\\", "/");
System.out.println("URL findResource(name): Reaplced to " + name); // just for you to debug
}
Handler.setUseFastConnectionExceptions(true);
try {
return super.findResource(name);
}
finally {
Handler.setUseFastConnectionExceptions(false);
}
}
....
}
关于java.lang.IllegalArgumentException : name 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51203893/