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 分钟前
Maven 公司内部私服中央仓库搭建 局域网仓库 资源共享 依赖包构建共享
java·maven
Auc246 分钟前
OJ判题系统第6期之判题逻辑开发——设计思路、实现步骤、代码实现(策略模式)
java·开发语言·docker·容器·策略模式
老李不敲代码11 分钟前
榕壹云搭子系统技术解析:基于Spring Boot+MySQL+UniApp的同城社交平台开发实践
spring boot·mysql·微信小程序·uni-app·软件需求
快乐肚皮14 分钟前
深入解析Docker:核心架构与最佳实践
java·运维·docker·容器
zhou18520 分钟前
MySQL保姆级安装教程(附资源包+5分钟极速配置+环境变量调试技巧)
java·python·mysql·php
小雅痞1 小时前
[Java][Leetcode middle] 55. 跳跃游戏
java·leetcode
com未来1 小时前
使用 NSSM 安装 Tomcat 11.0.6 为 Windows 服务
java·windows·tomcat
TDengine (老段)1 小时前
基于 TSBS 标准数据集下 TimescaleDB、InfluxDB 与 TDengine 性能对比测试报告
java·大数据·开发语言·数据库·时序数据库·tdengine·iotdb
养军博客1 小时前
spring boot3.0自定义校验注解:文章状态校验示例
java·前端·spring boot
lgily-12251 小时前
常用的设计模式详解
java·后端·python·设计模式