Spring Boot应用如何在actuator info端点展示依赖JAR的版本信息
Spring Boot 实现依赖版本写入Actuator Info端点方案
前置准备
首先确保项目已经引入Actuator依赖,以Maven为例:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
然后在配置文件中开启info端点暴露,以application.yml为例:
management: endpoints: web: exposure: include: info # 按需加入其他需要暴露的端点 endpoint: info: enabled: true
方案1:手动配置指定依赖版本(简单高效,推荐常规场景使用)
该方案适合依赖版本在构建配置中统一定义的场景,直接通过构建时变量替换自动注入版本:
- 在pom.xml(Maven)中统一定义你的依赖版本:
<properties> <custom-user-lib.version>2.3.1</custom-user-lib.version> <custom-order-lib.version>1.5.0</custom-order-lib.version> </properties> <dependencies> <dependency> <groupId>com.yourcompany</groupId> <artifactId>custom-user-lib</artifactId> <version>${custom-user-lib.version}</version> </dependency> <dependency> <groupId>com.yourcompany</groupId> <artifactId>custom-order-lib</artifactId> <version>${custom-order-lib.version}</version> </dependency> </dependencies>
- 在application.yml的info节点下直接引用构建变量:
info: dependencies: custom-user-lib: @custom-user-lib.version@ custom-order-lib: @custom-order-lib.version@
如果使用Gradle,变量替换语法为${custom-user-lib.version},无需用@包裹
构建项目后,变量会自动替换为实际使用的版本,访问/actuator/info即可直接看到。
方案2:自动扫描所有依赖版本(适合需要批量暴露版本的场景)
如果需要自动加载所有自定义依赖的版本,无需手动逐个配置,可以自定义InfoContributor实现:
- 编写自定义Info贡献者类:
import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; import java.io.IOException; import java.net.JarURLConnection; import java.net.URL; import java.util.Enumeration; import java.util.jar.Attributes; import java.util.jar.JarFile; @Component public class CustomDependencyInfoContributor implements InfoContributor { // 只扫描你公司内部的依赖包前缀,避免加载大量公共依赖 private static final String CUSTOM_LIB_PACKAGE_PREFIX = "com/yourcompany"; @Override public void contribute(Info.Builder builder) { try { Enumeration<URL> resources = Thread.currentThread().getContextClassLoader() .getResources(CUSTOM_LIB_PACKAGE_PREFIX); while (resources.hasMoreElements()) { URL url = resources.nextElement(); if (url.getProtocol().equals("jar")) { JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); try (JarFile jarFile = jarConnection.getJarFile()) { Attributes attributes = jarFile.getManifest().getMainAttributes(); String libName = jarFile.getName().substring(jarFile.getName().lastIndexOf("/") + 1); String version = attributes.getValue(Attributes.Name.IMPLEMENTATION_VERSION); if (version != null) { builder.withDetail("dependencies." + libName, version); } } } } } catch (IOException e) { // 异常处理逻辑按需添加 } } }
- 确保你的自定义Jar在构建时已经写入
Implementation-Version到MANIFEST.MF文件,否则无法读取到版本号。
效果验证
项目启动后访问GET /actuator/info接口,即可看到返回结果中包含依赖版本信息,示例:
{ "dependencies": { "custom-user-lib": "2.3.1", "custom-order-lib": "1.5.0" } }
内容的提问来源于stack exchange,提问作者PankajSays
相关产品推荐
相关产品推荐

