Spring Boot actuator 返回 404 not found

作者:编程家 分类: spring 时间:2025-09-30

使用Spring Boot开发Web应用时,我们经常会使用Spring Boot的Actuator模块来监控和管理我们的应用程序。Actuator提供了一组RESTful接口,通过这些接口我们可以查看应用程序的健康状况、性能指标等信息。然而,有时候我们可能会遇到一个问题,就是当访问Actuator的接口时,却返回了404 Not Found的错误。本文将探讨这个问题的可能原因,并提供解决方案。

问题分析

当我们使用Spring Boot的Actuator模块时,通常会在应用程序的pom.xml文件中添加相关的依赖。然后,我们就可以通过访问http://localhost:8080/actuator来查看应用程序的各种信息了。但是,在某些情况下,当我们访问该地址时,却返回了404 Not Found的错误。那么,什么可能导致这个问题呢?

可能的原因

1. Actuator模块未被正确添加到项目依赖中。在pom.xml文件中,我们需要添加如下依赖:

org.springframework.boot

spring-boot-starter-actuator

2. Actuator的端点路径未被正确配置。在application.properties或application.yml文件中,我们需要添加如下配置:

management.endpoints.web.base-path=/actuator

这样,我们就可以通过访问http://localhost:8080/actuator来访问Actuator的接口了。

3. Spring Security的配置导致了访问限制。在某些情况下,我们可能会使用Spring Security来保护我们的应用程序。如果没有正确配置Spring Security,它可能会拦截对Actuator的访问请求。

解决方案

根据可能的原因,我们可以采取以下解决方案:

1. 确保Actuator模块已正确添加到项目依赖中。可以通过检查pom.xml文件来确认是否存在以下依赖:

org.springframework.boot

spring-boot-starter-actuator

如果没有这个依赖,可以手动添加它。

2. 确保Actuator的端点路径已正确配置。可以在application.properties或application.yml文件中添加以下配置:

management.endpoints.web.base-path=/actuator

然后重新启动应用程序,尝试访问http://localhost:8080/actuator。

3. 检查Spring Security的配置。如果使用了Spring Security来保护应用程序,确保已正确配置了对Actuator的访问权限。可以在Spring Security的配置类中添加以下代码来允许对Actuator的访问:

@Configuration

@EnableWebSecurity

public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override

protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests()

.antMatchers("/actuator/**").permitAll()

.anyRequest().authenticated()

.and()

.formLogin().permitAll()

.and()

.logout().permitAll();

}

}

案例代码

以下是一个使用Spring Boot的Actuator模块的简单示例代码:

java

@RestController

public class HelloController {

@GetMapping("/hello")

public String hello() {

return "Hello, World!";

}

}

xml

org.springframework.boot

spring-boot-starter-actuator

properties

# application.properties

management.endpoints.web.base-path=/actuator

通过添加上述代码和配置,我们就可以在应用程序中使用Actuator模块了。访问http://localhost:8080/actuator可以查看应用程序的各种信息。

在使用Spring Boot的Actuator模块时,如果遇到了返回404 Not Found的错误,我们可以检查Actuator模块的依赖、端点路径的配置以及Spring Security的配置。通过逐一排查可能的原因,并采取相应的解决方案,我们可以解决这个问题,成功使用Actuator来监控和管理我们的应用程序。

希望本文对你有所帮助,祝你在使用Spring Boot和Actuator开发应用程序时顺利进行!