springboot 获取路径

java 复制代码
@PostConstruct
    public void setup() {

        try {

            // jar包所在目录  /Users/mashanshan

            String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
            System.out.println("path:" + path);  // file:/Users/mashanshan/manual-admin-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/

            ApplicationHome home = new ApplicationHome(getClass());
            File jarFile1 = home.getSource();
            String path0 = jarFile1.getParentFile().toString();
            System.out.println("path0: " + path0);  // /Users/mashanshan

            String path1 = ManualController.class.getClassLoader().getResource("").getPath();
            System.out.println("path1: " + path1);  // file:/Users/mashanshan/manual-admin-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/

            String path2 = System.getProperty("user.dir");
            System.out.println("path2:" + path2);  // /Users/mashanshan

            File path3 = new File(ResourceUtils.getURL("classpath:").getPath());
            System.out.println("path3:" + path3.getAbsolutePath());  // /Users/mashanshan/file:/Users/mashanshan/manual-admin-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!

            File path4 = new File("");
            System.out.println("path4:" + path4.getAbsolutePath());  ///Users/mashanshan

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

开发环境运行输出:

path:/Users/mashanshan/gitresp/manual-server/manual-admin/target/classes/

path0: /Users/mashanshan/gitresp/manual-server/manual-admin/target

path1: /Users/mashanshan/gitresp/manual-server/manual-admin/target/classes/

path2:/Users/mashanshan/gitresp/manual-server

path3:/Users/mashanshan/gitresp/manual-server/manual-admin/target/classes

path4:/Users/mashanshan/gitresp/manual-server

直接运行jar包输出:

path:file:/Users/mashanshan/manual-admin-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/

path0: /Users/mashanshan

path1: file:/Users/mashanshan/manual-admin-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/

path2:/Users/mashanshan

path3:/Users/mashanshan/file:/Users/mashanshan/manual-admin-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!

path4:/Users/mashanshan

相关推荐
咩咩啃树皮5 小时前
第40篇:Vue3组件化开发精讲——组件拆分、复用、父子通信、工程化架构
java·前端·架构
阳光是sunny5 小时前
LangGraph中的Reducer是什么
前端·人工智能·后端
灯澜忆梦5 小时前
GO_并发编程---定时器
开发语言·后端·golang
阳光是sunny5 小时前
从链到图:LangGraph 入门基础全解析
前端·人工智能·后端
鱟鲥鳚5 小时前
Spring Boot 集成 LangChain4j:从模型调用到 Tool Calling(Demo版)
java·spring boot
皮皮林5516 小时前
开源实力派,给本地 AI 装上深度调研能力,一张 3090 跑到 95.7 分!
后端
努力的小雨6 小时前
把 Windows 桌面图标做成一个会自己运转的小世界
后端
武子康7 小时前
Search Console Platform Properties 扩大 SEO 资产边界:从 Page Ranking 到 Topic Coverage(5 类误读边界 + 3 表数据层设计)
前端·人工智能·后端
大模型码小白7 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
腾渊信息科技公司7 小时前
Spring Boot对接MES实战:视觉检测数据自动同步方案
java·人工智能·spring boot·后端·计算机视觉·ai·软件需求