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

相关推荐
毕设源码-朱学姐9 小时前
【开题答辩全过程】以 爱心捐赠网站为例,包含答辩的问题和答案
java·eclipse
Pr Young9 小时前
服务优雅停止和服务优雅启动
后端
嘟嘟MD11 小时前
程序员副业 | 2025年9月复盘
后端·aigc
尘觉11 小时前
中秋节与 Spring Boot 的思考:一场开箱即用的团圆盛宴
java·spring boot·后端
间彧12 小时前
Seata分布式事务框架详解与项目实战
后端
Le1Yu12 小时前
2025-10-7学习笔记
java·笔记·学习
zhuyasen12 小时前
单机已达上限?PerfTest 分布式压测登场,轻松模拟百万用户洪峰
后端·性能优化·测试
勇哥java实战分享12 小时前
sensitive-word:一个简单易用的敏感词过滤框架
后端
popoxf12 小时前
spring容器启动流程(反射视角)
java·后端·spring
Funcy13 小时前
XxlJob 源码08:任务执行流程(三)之执行器揭秘
后端