1

I'm using a Spring Boot APP and I'm trying to set a System property programatically. I don't want to set the URL hardcoded, it must be loaded from the classpath

The problem is that my code runs well on IDE but when I try to execute the jar file I get:

 Exception in thread "main" java.lang.reflect.InvocationTargetException
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
         at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
         at org.springframework.boot.loader.Launcher.launch(Launcher.java:51)
         at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:52)
 Caused by: java.nio.file.FileSystemNotFoundException
         at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171)
         at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157)
         at java.nio.file.Paths.get(Unknown Source)

My Code:

public static void main(String[] args) {
    try {
        setSystemProperties();

        } catch (IOException e) {
            log.error("ERROR: Could not find my.properties file in classpath", e);
        }
    }

private static void setSystemProperties() throws IOException {
    ClassPathResource resource = new ClassPathResource("my.properties");
    System.setProperty("my.file", Paths.get(resource.getURI()).toString());
}
Hakan Dilek
  • 2,178
  • 2
  • 23
  • 35
  • 2
    `Paths.get(resource.getURI())` this is the issue. Can you compare what is the result of `resource.getURI()` when called from IDE and when called from `jar`? – Šimon Kocúrek Apr 08 '20 at 11:06
  • Given that it works in the IDE, this may be a matter of the location of the file it is trying to load. According to http://www.docjar.com/html/api/com/sun/nio/zipfs/ZipFileSystemProvider.java.html, the ZipFileSystemProvider may throw a FileSystemNotFoundException if it gets an IOException while trying to invoke toRealPath() internally. If you are defining the path to the file defined relatively, then make sure it is in the right relative location to where you are executing the code. Or, change the path to be canonical. – vsfDawg Apr 08 '20 at 11:44

1 Answers1

0

InvocationTargetException occurs when there's some underlying exception while calling method. Add the below catch block in your code to see the actual cause.

catch (InvocationTargetException e) {
        // the real cause
        e.getCause().printStackTrace();
}
Umais Gillani
  • 608
  • 4
  • 9