You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot运行时获取自身或依赖Jar路径的方法

解决Spring Boot中获取依赖Jar路径并扫描自定义注解类的方案

优先推荐:通过类加载器直接获取Y.jar的路径

不用硬编码配置路径,直接利用Y模块中任意类的类加载信息定位Jar,不管X.jar是打包运行还是解压状态都能适配:

import java.io.File;
import java.net.URL;
import com.yourpackage.HandlerA;

// 获取HandlerA所在的Jar/目录路径
URL codeSourceUrl = HandlerA.class.getProtectionDomain().getCodeSource().getLocation();
File yJarFile = new File(codeSourceUrl.getFile());
String yJarPath = yJarFile.getAbsolutePath();

拿到Y.jar路径后,可借助Spring的扫描工具定位带自定义注解的类:

import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import com.yourpackage.YourCustomAnnotation;

ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
scanner.addIncludeFilter(new AnnotationTypeFilter(YourCustomAnnotation.class));

// 扫描Y.jar下指定包的类
for (var beanDefinition : scanner.findCandidateComponents("com.yourpackage.y.module")) {
    Class<?> clazz = Class.forName(beanDefinition.getBeanClassName());
    YourCustomAnnotation annotation = clazz.getAnnotation(YourCustomAnnotation.class);
    // 处理注解逻辑
}

获取X.jar的完整路径(适用于需遍历整个Fat Jar的场景)

用Spring Boot自带的ApplicationHome类,直接拿到当前应用的Jar包或解压目录路径:

import org.springframework.boot.system.ApplicationHome;
import java.io.File;

ApplicationHome home = new ApplicationHome(YourSpringBootMainClass.class);
File xJarOrDir = home.getSource();
String xPath = xJarOrDir.getAbsolutePath();

// 分场景处理Y.jar路径
if (xJarOrDir.isFile()) {
    // 若X是Jar包,用JarFile遍历BOOT-INF/lib条目找Y.jar
} else {
    // 若X是解压目录,直接拼接路径获取Y.jar
    File yJarFile = new File(xJarOrDir, "BOOT-INF/lib/Y.jar");
    String yJarPath = yJarFile.getAbsolutePath();
}

配置文件方式的补充(仅特殊场景使用)

如果必须用application.properties配置路径,可按以下方式实现,但需注意换环境要同步修改配置:

  1. 在配置文件中添加:
# 可选配置X.jar路径或直接配置Y.jar路径
app.x.jar.path=/path/to/X.jar
# 或者
app.y.jar.path=/path/to/Y.jar
  1. 代码中通过@Value注入路径:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class JarPathHolder {
    @Value("${app.y.jar.path}")
    private String yJarPath;

    // 后续业务逻辑中使用该路径
}

内容的提问来源于stack exchange,提问作者Arkadiusz Górecki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 08:27:41