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");
        }
    }
阅读 2.8k
2 个回答
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;
    }
}
  1. 外部程序 和 你的 jar 包是什么关系?
  2. 如果没有啥直接关系,可以考虑用配置文件,把外部程序的路径配置进去
  3. 如果有直接关系,就把外部程序放到 resource 里,或者某个特定的相对路径,或者某个特定的绝对路径下即可
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题