
spring boot actuator 提供了许多生产就绪的特性,帮助我们监控和管理应用程序。其中 /info 端点是一个非常有用的功能,可以展示关于应用程序的通用信息,如版本、构建时间、git提交id等。然而,有时默认配置并不能直接显示期望的应用版本信息,尤其是在从 pom.xml 中动态获取时。本教程将指导您如何正确配置 /info 端点以显示应用程序的详细元数据。
首先,确保您的项目中包含了 Spring Boot Actuator 的核心依赖。这个依赖是启用 Actuator 端点功能的基础。
在 pom.xml 文件中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>这个 starter 依赖会引入所有必要的 Actuator 组件,包括 /info 端点。
要让 /info 端点显示自定义的应用信息,如名称、描述和版本,我们需要在 application.yml(或 application.properties)文件中进行相应的配置。关键在于启用 env 信息并定义 info.application 部分。
management:
info:
env:
enabled: true # 确保 Actuator 能够读取环境信息,包括 Maven 项目属性
endpoints:
web:
exposure:
include: info # 暴露 info 端点
base-path: /public/actuator # 可选:自定义 Actuator 端点的基础路径
info:
application:
name: '@project.name@' # 从 pom.xml 中获取项目名称
description: '@project.description@' # 从 pom.xml 中获取项目描述
version: '@project.version@' # 从 pom.xml 中获取项目版本配置说明:
如果您的 Spring Boot 应用程序集成了 Spring Security,那么默认情况下,Actuator 端点可能需要认证才能访问。为了让 /info 端点(或您自定义的 Actuator 基础路径下的端点)可以公开访问,您需要配置 Spring Security 允许对这些路径进行匿名访问。
以下是一个示例配置,允许对 /public/** 路径(对应 base-path: /public/actuator)的 GET 请求进行匿名访问:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// ... 其他安全配置
.authorizeHttpRequests(customizer -> customizer
// 允许对 /public/** 路径的 GET 请求进行匿名访问
.requestMatchers(HttpMethod.GET, "/public/**").permitAll()
// 其他所有请求需要认证
.anyRequest().authenticated()
)
// ... 其他安全配置
.csrf(csrf -> csrf.disable()); // 示例:禁用CSRF保护,根据实际需求配置
return httpSecurity.build();
}
}注意事项:
完成上述配置后,您可以启动您的 Spring Boot 应用程序。
您应该会看到一个 JSON 响应,其中包含您在 application.yml 中配置的应用信息,并且 name、description 和 version 字段将正确显示从 pom.xml 获取的值。
示例输出:
{
"application": {
"name": "Spring Sample Application",
"description": "A Spring Boot application example",
"version": "1.0.0-SNAPSHOT"
}
}通过遵循本教程的步骤,您可以轻松地在 Spring Boot 应用程序中配置 Actuator 的 /info 端点,以显示动态获取的应用程序版本、名称和描述信息。这不仅有助于应用程序的监控和管理,还能确保这些元数据与项目的构建信息保持一致。记住,正确配置 management.info.env.enabled 和处理 Spring Security 访问权限是成功实现此功能的关键。
以上就是Spring Boot Actuator /info 端点应用版本信息显示教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号