0

How to load jar file (the one the app was launched from) or get it's path at runtime?

Or

How to get a dependency jar at runtime from BOOT-INF/lib directory?

Our use case is that we have a Spring Boot jar file named X.jar, which is the application we are running. It has a jar dependency in BOOT-INF/lib directory called Y.jar. Y module has many classes (HandlerA.java, HandlerB.java, etc.) that are annotated with our custom annotations. We need to be able to get those classes at runtime and we have to access their annotations via reflection.

We either need a full path to X.jar, and then we can stream its entries in order to find Y.jar by its name

Or

We need a full path to Y.jar

(currently the X.jar is unpacked in our environment so we can access Y.jar directly in filesystem but that is likely to change)

Then we can make instance of JarFile from Y.jar and stream its JarEntry-s to find all Handler classes.

Currently, I am trying an approach where we configure a Spring property in application.properties file to provide a full path to either X.jar or Y.jar, since we know were they are.

5
  • Is it perhaps possible to use proper indexing, like smallrye.io/blog/jandex-3-0-0? You'd have to do that when building Y.jar though. Commented Apr 26 at 12:26
  • If not you can try to use ProtectionDomain. Take an existing class from either X.jar or Y.jar (let's call it A), then you can get a URL to it using A.class.getProtectionDomain().getCodeSource().getLocation(). For files inside a JAR that's going to return something like jar:<URL-to-jar>!<path-inside-jar> so you'd have to use some code to be able to access it. For instance: try (FileSystem fs = FileSystems.newFileSystem(Paths.get(location.toURI()), <some class loader>)) { ... }, then fs.getPath("/") returns the root folder of the JAR file. Commented Apr 26 at 12:31
  • @RobSpoor Do I have to create some custom FileSystemProvider implementation and create a config file in META-INF/services (for ServiceLoader) for this to work? Commented Apr 28 at 14:39
  • My little code snippet assumes that the URL refers directly to a JAR file, so you may have to tweak it a bit. You may have to use 2 nested file systems if you have a JAR in a JAR. JAR files are essentially ZIP files, and support for that is built into the JRE. Commented Apr 28 at 18:42
  • I think I have made a bad approach to my problem. I do not have to care about nested jars and accessing them. This answer satisfies our use case for now stackoverflow.com/a/1312775/16505995 Commented Apr 30 at 15:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.