Skip to main content

Implementing Custom Actuator Endpoint

Spring Boot provides actuator endpoints that allows you to monitor or manage your application over JMX or HTTP. To add custom endpoint annotate Spring bean with @Endpoint.

package org.example.demo.actuate;

import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

import java.lang.management.ManagementFactory;

@Component
@Endpoint(id = "uptime") // (1)
public class UptimeEndpoint {

@ReadOperation // (2)
public Uptime getUptime() {
var runtime = ManagementFactory.getRuntimeMXBean();

return new Uptime(runtime.getUptime(), runtime.getStartTime());
}

private record Uptime(long uptime, long startTime) { }

}
  1. @Endpoint marks the class as Actuator endpoint. For HTTP endpoints id specifies the path - actuator/uptime in this example.
  2. @ReadOperation marks the method as read operation. You can also use @WriteOperation and @DeleteOperation for respectively write and delete operations.

Accessing the endpoint:

$ curl 'http://localhost:8080/actuator/uptime' -i -X GET

would return the uptime in JSON format:

{"uptime":4285,"startTime":1701599039405}

For more information check the reference guide.

Troubleshooting

The code does not compile

Make sure that you have included the starter-actuator dependency:

build.gradle.kts
implementation("org.springframework.boot:spring-boot-starter-actuator")

/actuator/uptime returns 404 (Not Found)

Due to security considerations, most endpoint by default are disabled over HTTP. You can enable all endpoints (after you read the docs) by setting management.endpoints.web.exposure.include:

application.properties
management.endpoints.web.exposure.include=*