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.
Y.jarthough.ProtectionDomain. Take an existing class from eitherX.jarorY.jar(let's call itA), then you can get a URL to it usingA.class.getProtectionDomain().getCodeSource().getLocation(). For files inside a JAR that's going to return something likejar:<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>)) { ... }, thenfs.getPath("/")returns the root folder of the JAR file.