springboot如何简单的获取开发时的项目根路径,打jar包后获取的也是根路径?
场景如下:在我的项目根路径下有几个外部程序、脚本,我需要在开发环境获取项目的根目录,如我的项目名为project-a,此时获取的是xxx/project-a/打成jar包后是jar包所在目录的父路径,也是xxx/project-a/
有没有什么简单的方法呢?自己这个还是感觉有点缺陷
public static String getAppRootPath(){
String activeProfile = SpringUtil.getActiveProfile();
if ("prod".equals(activeProfile)){
return XXXApplication.class.getProtectionDomain().getCodeSource().getLocation().getPath();
}else {
return System.getProperty("user.dir");
}
}
回复
1个回答

test
2024-06-29
public static String getAppRootPath() {
try {
File jarDir = new File(ClassUtils.getDefaultClassLoader().getResource("").getPath());
if (jarDir.getAbsolutePath().endsWith(".jar")) {
return jarDir.getParentFile().getAbsolutePath();
} else {
return System.getProperty("user.dir");
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容