小编典典

如何动态获取Spring Boot Application Jar的父文件夹路径?

spring-boot

我有一个使用 java -jar application.jar 运行的spring boot Web应用 程序
。我需要从代码动态获取jar父文件夹路径。我该怎么做?

我已经尝试过了,但是没有成功。


阅读 432

收藏
2020-05-30

共1个答案

小编典典

嗯,对我有用的是对该答案的改编。代码是:

如果使用java -jar myapp.jar进行运行,dirtyPath将接近以下内容:jar:file:/
D:/arquivos/repositorio/myapp/trunk/target/myapp-1.0.3-RELEASE.jar!/ BOOT-
INF / classes!/ br / com / cancastilho / service。或者,如果您从Spring Tools
Suit运行,则如下所示:file:/ D:/ arquivos / repositorio / myapp / trunk / target /
classes / br / com / cancastilho / service

public String getParentDirectoryFromJar() {
    String dirtyPath = getClass().getResource("").toString();
    String jarPath = dirtyPath.replaceAll("^.*file:/", ""); //removes file:/ and everything before it
    jarPath = jarPath.replaceAll("jar!.*", "jar"); //removes everything after .jar, if .jar exists in dirtyPath
    jarPath = jarPath.replaceAll("%20", " "); //necessary if path has spaces within
    if (!jarPath.endsWith(".jar")) { // this is needed if you plan to run the app using Spring Tools Suit play button. 
        jarPath = jarPath.replaceAll("/classes/.*", "/classes/");
    }
    String directoryPath = Paths.get(jarPath).getParent().toString(); //Paths - from java 8
    return directoryPath;
}

编辑:

实际上,如果您使用的是Spring
Boot,则可以像这样使用ApplicationHome类:

ApplicationHome home = new ApplicationHome(MyMainSpringBootApplication.class);
home.getDir();    // returns the folder where the jar is. This is what I wanted.
home.getSource(); // returns the jar absolute path.
2020-05-30