首页 帮助中心 常见问题 SpringBoot项目jar包发布后获取jar包所在路径的方法
SpringBoot项目jar包发布后获取jar包所在路径的方法
时间 : 2024-09-09 10:29:24 编辑 : 华纳云 阅读量 : 69

在部署SpringBoot项目中,可以通过多个方式来获取运行时的JAR包所在的路径。如可以使用ProtectionDomain

,这种方法可以获取类所在的JAR文件路径:

import java.io.File;

import java.net.URISyntaxException;

 

public class JarLocationUtil {

    public static void main(String[] args) {

        try {

            File jarFile = new File(JarLocationUtil.class.getProtectionDomain().getCodeSource().getLocation().toURI());

            String jarPath = jarFile.getAbsolutePath();

            System.out.println("JAR 文件路径: " + jarPath);

        } catch (URISyntaxException e) {

            e.printStackTrace();

        }

    }

}

 

或者是还可以通过使用 ApplicationHome 类。SpringBoot提供了ApplicationHome 类,可以很轻松的获取到JAR文件路径:

import org.springframework.boot.system.ApplicationHome;

 

public class JarLocationUtil {

    public static void main(String[] args) {

        ApplicationHome home = new ApplicationHome(JarLocationUtil.class);

        File jarFile = home.getSource();

        String jarPath = jarFile.getAbsolutePath();

        System.out.println("JAR 文件路径: " + jarPath);

    }

}

使用Java NIO,这是一种利用 Path 和 URI 类来获取 JAR 文件路径的方法:

import java.nio.file.Path;

import java.nio.file.Paths;

 

public class JarLocationUtil {

    public static void main(String[] args) {

        Path path = Paths.get(JarLocationUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath());

        String jarPath = path.toAbsolutePath().toString();

        System.out.println("JAR 文件路径: " + jarPath);

    }

}

以上就是华纳云分享的全部方式,都可以在Spring Boot项目中使用,只要使用其中一种即可。更推荐的是ApplicationHome 类,这是Spring Boot提供的工具类,所以使用起来会更方便。

 

华纳云 推荐文章
使用Dockerfile创建支持SSH服务的镜像的步骤 Linux快速部署DHCP服务器详细步骤 Linux使用pushd和popd高效切换目录 Windows上使用C#访问Ubuntu上Redis数据库 如何使用Bash补全功能简化linux和Docker命令行 如何使用SSHFS挂载远程目录 Linux中使用dd完成低级数据复制 Linux中显示和管理IP地址设置 如何在Ubuntu上安装Deepin桌面环境 Ubuntu 16.04.1上搭建Redis分布式集群并使用C#操作
客服咨询
7*24小时技术支持
技术支持
渠道支持