Spring Boot Actuator: watching and controlling a running application

Actuator gives a running Spring Boot application endpoints for health, build info, metrics, configuration and log levels. This page runs each one against a live server, shows what is exposed by default and why, and builds health groups, a custom endpoint and role-based security around them.

Contents

What Spring Boot Actuator adds

A running application should be able to answer questions from the outside: is it healthy, which version is deployed, how many requests has it served, which configuration value is in effect, and what are its threads doing. Spring Boot Actuator answers them through endpoints, small built-in operations that each expose one kind of information.

Adding spring-boot-starter-actuator brings three parts:

  • Endpoints: health, info, metrics, env, loggers and more. Each is a bean with read and write operations, independent of any transport.
  • Exposure: the endpoints are published over HTTP under /actuator, and over JMX. By default only health is published, because the others can reveal internals.
  • Micrometer: the metrics library behind /actuator/metrics. Spring Boot registers JVM, process and HTTP meters automatically, and your code adds its own through MeterRegistry.
The endpoints used most often
EndpointShowsTypical consumer
healthUP or DOWN, with optional details per componentLoad balancers, Kubernetes probes
infoVersion, build and git data, custom detailsDashboards, release checks
metricsMeters by name, with tagsPeople exploring; scrapers use prometheus or OTLP export
env, configpropsProperty sources and bound configuration, sanitisedDebugging configuration
loggersLog levels, changeable at runtimeDebugging production
threaddump, heapdumpThread stacks, a heap snapshotDiagnosing hangs and leaks
mappings, beans, conditionsRequest mappings, beans, auto-configuration decisionsUnderstanding the application

The programs on this page run Spring Boot 4.1.2 with Spring MVC on a random port, call the endpoints with java.net.http.HttpClient, and print status codes and bodies. Spring Boot 4 moved the health API to a module of its own: HealthIndicator and Health are now in org.springframework.boot.health.contributor, not org.springframework.boot.actuate.health as in Spring Boot 3, so imports need updating when you upgrade.

What is exposed by default

The same application runs twice, first with no actuator settings and then with every endpoint exposed, and asks for four endpoints each time:

Java
package actuator.basics;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;

@SpringBootApplication
public class ActuatorBasics {

    static final HttpClient HTTP = HttpClient.newHttpClient();

    static HttpResponse<String> get(int port, String path) throws Exception {
        HttpRequest request = HttpRequest.newBuilder(
                URI.create("http://localhost:" + port + path)).build();
        return HTTP.send(request, HttpResponse.BodyHandlers.ofString());
    }

    static void run(String label, Map<String, Object> properties) throws Exception {
        System.out.println(label);
        SpringApplication app = new SpringApplication(ActuatorBasics.class);
        app.setDefaultProperties(properties);
        try (var context = app.run()) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            JsonNode links = JsonMapper.shared().readTree(get(port, "/actuator").body())
                    .get("_links");
            System.out.println("  GET /actuator lists: " + new TreeSet<>(links.propertyNames()));
            for (String path : new String[] {"/actuator/health", "/actuator/info",
                    "/actuator/env", "/actuator/beans"}) {
                HttpResponse<String> response = get(port, path);
                String body = response.statusCode() == 404 ? "" : response.body();
                System.out.println("  GET " + path + " -> " + response.statusCode() + " "
                        + (body.length() > 60 ? body.substring(0, 60) + "..." : body));
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Map<String, Object> base = Map.of(
                "server.port", "0",
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN");
        run("1. Defaults:", base);

        var all = new HashMap<>(base);
        all.put("management.endpoints.web.exposure.include", "*");
        run("2. management.endpoints.web.exposure.include=*", all);
    }
}
Output
1. Defaults:
  GET /actuator lists: [health, health-path, self]
  GET /actuator/health -> 200 {"groups":["liveness","readiness"],"status":"UP"}
  GET /actuator/info -> 404 
  GET /actuator/env -> 404 
  GET /actuator/beans -> 404 
2. management.endpoints.web.exposure.include=*
  GET /actuator lists: [beans, conditions, configprops, configprops-prefix, env, env-toMatch, health, health-path, info, loggers, loggers-name, mappings, metrics, metrics-requiredMetricName, sbom, sbom-id, scheduledtasks, self, threaddump]
  GET /actuator/health -> 200 {"groups":["liveness","readiness"],"status":"UP"}
  GET /actuator/info -> 200 {}
  GET /actuator/env -> 200 {"activeProfiles":[],"defaultProfiles":["default"],"property...
  GET /actuator/beans -> 200 {"contexts":{"application":{"beans":{"endpointCachingOperati...
  • With the defaults, /actuator listed only health (plus health-path, the link template for one component, and self). info, env and beans returned 404: they exist, but are not exposed over HTTP.
  • The health response shows only the overall status and the names of two groups, liveness and readiness. Details are hidden unless you ask for them.
  • With exposure.include=*, 12 endpoints appeared, including sbom, which serves the software bill of materials when the build produces one. The -name, -prefix and -toMatch entries are link templates for one item.
  • info now answered, but with {}: nothing contributes to it until you configure it, as a later section shows.
  • heapdump and shutdown are missing even with *. Access to those two is restricted by default, and management.endpoint.<id>.access=unrestricted grants it.

Exposure and access are separate settings. management.endpoints.web.exposure.include and exclude decide what is reachable over HTTP. management.endpoint.<id>.access, with the values none, read-only and unrestricted, decides what an endpoint may do at all; it replaced the older management.endpoint.<id>.enabled property in Spring Boot 3.4. Avoid * in production: list the endpoints you need.

Health checks, groups and probes

Health is the endpoint other systems depend on. An order service that calls a payment gateway is a typical case: the program adds a health indicator for the gateway, turns the gateway off halfway, and then marks the application as not ready:

Java
package actuator.health;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.availability.AvailabilityChangeEvent;
import org.springframework.boot.availability.ReadinessState;
import org.springframework.boot.health.contributor.Health;
import org.springframework.boot.health.contributor.HealthIndicator;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.stereotype.Component;
import tools.jackson.databind.SerializationFeature;
import tools.jackson.databind.json.JsonMapper;

@SpringBootApplication
public class HealthChecks {

    @Component("paymentGatewayHealthIndicator")
    static class PaymentGatewayHealthIndicator implements HealthIndicator {
        final AtomicBoolean reachable = new AtomicBoolean(true);

        @Override
        public Health health() {
            if (reachable.get()) {
                return Health.up().withDetail("provider", "stripe").build();
            }
            return Health.down().withDetail("provider", "stripe")
                    .withDetail("error", "connect timed out").build();
        }
    }

    static final HttpClient HTTP = HttpClient.newHttpClient();
    static final JsonMapper PRETTY = JsonMapper.builder()
            .enable(SerializationFeature.INDENT_OUTPUT).build();

    static void get(int port, String path, boolean pretty) throws Exception {
        HttpRequest request = HttpRequest.newBuilder(
                URI.create("http://localhost:" + port + path)).build();
        HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println("GET " + path + " -> " + response.statusCode());
        System.out.println(pretty
                ? PRETTY.writeValueAsString(PRETTY.readTree(response.body()))
                : "  " + response.body());
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(HealthChecks.class);
        app.setDefaultProperties(Map.of(
                "server.port", "0",
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "management.health.diskspace.enabled", "false",
                "management.health.ssl.enabled", "false",
                "management.endpoint.health.show-details", "always",
                "management.endpoint.health.group.checkout.include", "paymentGateway,ping"));
        try (var context = app.run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            get(port, "/actuator/health", true);

            context.getBean(PaymentGatewayHealthIndicator.class).reachable.set(false);
            System.out.println("-- payment gateway goes down --");
            get(port, "/actuator/health/checkout", false);
            get(port, "/actuator/health/liveness", false);

            System.out.println("-- application refuses traffic --");
            AvailabilityChangeEvent.publish(context, ReadinessState.REFUSING_TRAFFIC);
            get(port, "/actuator/health/readiness", false);
        }
    }
}
Output
GET /actuator/health -> 200
{
  "components" : {
    "livenessState" : {
      "status" : "UP"
    },
    "paymentGateway" : {
      "details" : {
        "provider" : "stripe"
      },
      "status" : "UP"
    },
    "ping" : {
      "status" : "UP"
    },
    "readinessState" : {
      "status" : "UP"
    }
  },
  "groups" : [ "checkout", "liveness", "readiness" ],
  "status" : "UP"
}
-- payment gateway goes down --
GET /actuator/health/checkout -> 503
  {"components":{"paymentGateway":{"details":{"provider":"stripe","error":"connect timed out"},"status":"DOWN"},"ping":{"status":"UP"}},"status":"DOWN"}
GET /actuator/health/liveness -> 200
  {"status":"UP"}
-- application refuses traffic --
GET /actuator/health/readiness -> 503
  {"status":"OUT_OF_SERVICE"}
  • The bean paymentGatewayHealthIndicator appears as the component paymentGateway: Spring Boot drops the HealthIndicator suffix from the bean name.
  • With show-details=always, each component and its details are listed. ping always reports UP, and livenessState and readinessState reflect the application's availability state.
  • Once the gateway was down, the custom checkout group, which includes only paymentGateway and ping, returned HTTP 503 with status DOWN. A DOWN or OUT_OF_SERVICE status maps to 503 by default, so a load balancer stops sending traffic without parsing the body.
  • The liveness group still returned 200. It contains only livenessState, so a broken dependency did not tell Kubernetes to restart a process that is otherwise fine.
  • After AvailabilityChangeEvent.publish(context, ReadinessState.REFUSING_TRAFFIC), readiness returned 503 with OUT_OF_SERVICE. Spring Boot publishes the same event itself while the application starts and shuts down.

Keep liveness free of external checks: if the database is down, restarting every instance will not fix it. Put dependencies that must be available before taking traffic in the readiness group with management.endpoint.health.group.readiness.include=readinessState,db. A group that names a missing indicator stops the application at startup, which catches typos. Health checks run on every request to the endpoint, so a slow check slows the probe too; keep them quick and cheap.

Info and env: what is deployed and how it is configured

An info response with the application name and version is the quickest release check, and env shows where a value came from. The program also defines an API key, to see what env does with secrets:

Java
package actuator.info;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.stereotype.Component;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;

@SpringBootApplication
public class InfoAndEnv {

    @Component
    static class FeatureFlagsInfo implements InfoContributor {
        @Override
        public void contribute(Info.Builder builder) {
            builder.withDetail("features", Map.of("newCheckout", true));
        }
    }

    static final HttpClient HTTP = HttpClient.newHttpClient();

    static String get(int port, String path) throws Exception {
        HttpRequest request = HttpRequest.newBuilder(
                URI.create("http://localhost:" + port + path)).build();
        HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println("  GET " + path + " -> " + response.statusCode());
        return response.body();
    }

    static void run(String label, String showValues) throws Exception {
        System.out.println(label);
        Map<String, Object> props = new HashMap<>(Map.of(
                "server.port", "0",
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "management.endpoints.web.exposure.include", "info,env",
                "management.info.env.enabled", "true",
                "info.app.name", "order-service",
                "info.app.version", "1.4.2",
                "payment.api-key", "sk_live_51H8"));
        if (showValues != null) {
            props.put("management.endpoint.env.show-values", showValues);
        }
        SpringApplication app = new SpringApplication(InfoAndEnv.class);
        app.setDefaultProperties(props);
        try (var context = app.run()) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            System.out.println("    " + get(port, "/actuator/info"));
            JsonNode env = JsonMapper.shared().readTree(get(port, "/actuator/env/payment.api-key"));
            System.out.println("    property: " + env.get("property"));
        }
    }

    public static void main(String[] args) throws Exception {
        run("1. Default sanitising:", null);
        run("2. management.endpoint.env.show-values=always:", "always");
    }
}
Output
1. Default sanitising:
  GET /actuator/info -> 200
    {"app":{"version":"1.4.2","name":"order-service"},"features":{"newCheckout":true}}
  GET /actuator/env/payment.api-key -> 200
    property: {"source":"defaultProperties","value":"******"}
2. management.endpoint.env.show-values=always:
  GET /actuator/info -> 200
    {"app":{"version":"1.4.2","name":"order-service"},"features":{"newCheckout":true}}
  GET /actuator/env/payment.api-key -> 200
    property: {"source":"defaultProperties","value":"sk_live_51H8"}
  • info.app.name and info.app.version appeared under app because management.info.env.enabled=true switches on the contributor that copies every info.* property. It has been off by default since Spring Boot 2.6.
  • The features entry came from the custom InfoContributor bean, which can add any data computed at request time.
  • /actuator/env/payment.api-key named the source, defaultProperties, but returned the value as ******. Every value is masked by default.
  • With show-values=always, the real key was returned to anyone who can reach the endpoint. Use when-authorized with a role instead, as the security section shows.

Two more contributors are on by default but need input from the build: build reads META-INF/build-info.properties, written by the build-info goal of the Spring Boot Maven plugin or the springBoot.buildInfo() Gradle task, and git reads git.properties from a git commit plugin. The java, os and process contributors are off by default.

Metrics and runtime log levels

An order endpoint with its own counter and a debug log line shows the two endpoints used most when something goes wrong in production. The debug line only appears once the log level is raised through loggers:

Java
package actuator.metrics;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;

@SpringBootApplication
public class MetricsAndLoggers {

    @RestController
    static class OrderController {
        private static final Logger log = LoggerFactory.getLogger(OrderController.class);
        private final Counter placed;

        OrderController(MeterRegistry registry) {
            this.placed = Counter.builder("orders.placed")
                    .tag("channel", "web")
                    .description("Orders accepted")
                    .register(registry);
        }

        @PostMapping("/orders")
        String place() {
            placed.increment();
            log.debug("order accepted, total so far {}", (long) placed.count());
            return "ok";
        }
    }

    static final HttpClient HTTP = HttpClient.newHttpClient();

    static String call(int port, String method, String path, String json) throws Exception {
        HttpRequest.Builder builder = HttpRequest.newBuilder(
                URI.create("http://localhost:" + port + path));
        if (json != null) {
            builder.header("Content-Type", "application/json");
        }
        builder.method(method, json == null ? HttpRequest.BodyPublishers.noBody()
                : HttpRequest.BodyPublishers.ofString(json));
        HttpResponse<String> response = HTTP.send(builder.build(),
                HttpResponse.BodyHandlers.ofString());
        System.out.println(method + " " + path + " -> " + response.statusCode());
        System.out.flush();
        return response.body();
    }

    static JsonNode json(String body) {
        return JsonMapper.shared().readTree(body);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(MetricsAndLoggers.class);
        app.setDefaultProperties(Map.of(
                "server.port", "0",
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "spring.main.log-startup-info", "false",
                "logging.level.actuator.metrics", "INFO",
                "logging.pattern.console", "  log: %level %logger{0} - %m%n",
                "management.endpoints.web.exposure.include", "health,metrics,loggers"));
        try (var context = app.run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            String logger = "/actuator/loggers/actuator.metrics.MetricsAndLoggers$OrderController";

            call(port, "POST", "/orders", null);
            System.out.println("  " + json(call(port, "GET", logger, null)));

            call(port, "POST", logger, "{\"configuredLevel\":\"DEBUG\"}");
            call(port, "POST", "/orders", null);
            call(port, "POST", "/orders", null);
            System.out.println("  " + json(call(port, "GET", logger, null)));

            JsonNode orders = json(call(port, "GET", "/actuator/metrics/orders.placed", null));
            System.out.println("  measurements: " + orders.get("measurements"));
            System.out.println("  tags:         " + orders.get("availableTags"));

            JsonNode http = json(call(port, "GET",
                    "/actuator/metrics/http.server.requests?tag=uri:/orders", null));
            System.out.println("  COUNT for uri=/orders: "
                    + http.get("measurements").get(0).get("value"));
            JsonNode names = json(call(port, "GET", "/actuator/metrics", null)).get("names");
            for (String name : new String[] {"jvm.memory.used", "jvm.threads.live",
                    "process.cpu.usage", "tomcat.sessions.active.current"}) {
                boolean found = false;
                for (JsonNode n : names) {
                    found |= n.asString().equals(name);
                }
                System.out.println("  " + name + " listed: " + found);
            }
        }
    }
}
Output
POST /orders -> 200
GET /actuator/loggers/actuator.metrics.MetricsAndLoggers$OrderController -> 200
  {"effectiveLevel":"INFO"}
POST /actuator/loggers/actuator.metrics.MetricsAndLoggers$OrderController -> 204
  log: DEBUG MetricsAndLoggers$OrderController - order accepted, total so far 2
POST /orders -> 200
  log: DEBUG MetricsAndLoggers$OrderController - order accepted, total so far 3
POST /orders -> 200
GET /actuator/loggers/actuator.metrics.MetricsAndLoggers$OrderController -> 200
  {"configuredLevel":"DEBUG","effectiveLevel":"DEBUG"}
GET /actuator/metrics/orders.placed -> 200
  measurements: [{"statistic":"COUNT","value":3.0}]
  tags:         [{"tag":"channel","values":["web"]}]
GET /actuator/metrics/http.server.requests?tag=uri:/orders -> 200
  COUNT for uri=/orders: 3.0
GET /actuator/metrics -> 200
  jvm.memory.used listed: true
  jvm.threads.live listed: true
  process.cpu.usage listed: true
  tomcat.sessions.active.current listed: true
  • The first order produced no log line: the controller's logger was at INFO. GET /actuator/loggers/... showed only an effectiveLevel, inherited from a parent logger.
  • POST with {"configuredLevel":"DEBUG"} returned 204, and the next two orders logged at DEBUG. The logger now reports both a configured and an effective level. Posting {"configuredLevel":null} resets it.
  • orders.placed counted all 3 orders, including the one before the level change, and lists its channel tag with the value web.
  • http.server.requests, recorded automatically for every request, filtered with ?tag=uri:/orders, also counted 3. The uri tag holds the route template, not the raw path, so /orders/{id} stays one series.
  • JVM memory, thread, CPU and Tomcat meters were registered without any code.

The metrics endpoint is for people. Monitoring systems pull or receive metrics through a registry: micrometer-registry-prometheus adds a prometheus endpoint for scraping, and the OTLP registry pushes metrics to an OpenTelemetry collector. The observability page covers both. A log level changed through loggers lasts until the application restarts and applies to one instance only.

Writing your own endpoint

Operational controls that are specific to your application, such as feature flags, fit an endpoint of their own. The program also moves all actuator endpoints to a separate management port, which keeps them away from public traffic:

Java
package actuator.custom;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.Selector;
import org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class CustomEndpoint {

    @Component
    @Endpoint(id = "features")
    static class FeaturesEndpoint {
        private final Map<String, Boolean> flags = new ConcurrentHashMap<>(
                Map.of("newCheckout", false, "giftCards", true));

        @ReadOperation
        Map<String, Boolean> all() {
            return new TreeMap<>(flags);
        }

        @ReadOperation
        Boolean one(@Selector String name) {
            return flags.get(name);
        }

        @WriteOperation
        void set(@Selector String name, boolean enabled) {
            flags.put(name, enabled);
        }
    }

    static final HttpClient HTTP = HttpClient.newHttpClient();

    static void call(int port, String label, String method, String path, String json)
            throws Exception {
        HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:" + port + path))
                .header("Content-Type", "application/json")
                .method(method, json == null ? HttpRequest.BodyPublishers.noBody()
                        : HttpRequest.BodyPublishers.ofString(json))
                .build();
        HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
        String body = response.statusCode() == 404 ? "" : response.body();
        System.out.println(label + " " + method + " " + path + " -> "
                + response.statusCode() + " " + body);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(CustomEndpoint.class);
        app.setDefaultProperties(Map.of(
                "server.port", "0",
                "management.server.port", "0",
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "management.endpoints.web.exposure.include", "health,features"));
        try (var context = app.run(args)) {
            int appPort = ((WebServerApplicationContext) context).getWebServer().getPort();
            int mgmtPort = context.getEnvironment()
                    .getRequiredProperty("local.management.port", Integer.class);
            System.out.println("separate ports: " + (appPort != mgmtPort));

            call(appPort, "[app] ", "GET", "/actuator/health", null);
            call(mgmtPort, "[mgmt]", "GET", "/actuator/health", null);
            call(mgmtPort, "[mgmt]", "GET", "/actuator/features", null);
            call(mgmtPort, "[mgmt]", "POST", "/actuator/features/newCheckout",
                    "{\"enabled\": true}");
            call(mgmtPort, "[mgmt]", "GET", "/actuator/features/newCheckout", null);
            call(mgmtPort, "[mgmt]", "GET", "/actuator/features/unknown", null);
        }
    }
}
Output
separate ports: true
[app]  GET /actuator/health -> 404 
[mgmt] GET /actuator/health -> 200 {"groups":["liveness","readiness"],"status":"UP"}
[mgmt] GET /actuator/features -> 200 {"giftCards":true,"newCheckout":false}
[mgmt] POST /actuator/features/newCheckout -> 204 
[mgmt] GET /actuator/features/newCheckout -> 200 true
[mgmt] GET /actuator/features/unknown -> 404
  • With management.server.port set, the endpoints moved to a second port: /actuator/health on the application port returned 404, and on the management port 200. The real port numbers are random here, so the program only checks that they differ.
  • @Endpoint(id = "features") became /actuator/features, once listed in exposure.include. The @ReadOperation without parameters answered GET /actuator/features.
  • A @Selector parameter becomes a path segment, so GET /actuator/features/newCheckout called one("newCheckout").
  • The @WriteOperation took enabled from the JSON body and returned 204, because it returns nothing. The flag then read true.
  • For an unknown name, one returned null, which Actuator turns into 404.

The same endpoint is also published over JMX when spring.jmx.enabled=true and JMX exposure includes it, because the operations are not tied to HTTP. @DeleteOperation maps to HTTP DELETE. For an endpoint that only makes sense over HTTP, @WebEndpoint restricts it to the web.

Securing the endpoints

With Spring Security on the classpath, Spring Boot secures every actuator endpoint except health by default. Most applications want a rule of their own: health open for probes, everything else for an operations role. This program uses EndpointRequest, which matches actuator paths wherever they are mapped:

Java
package actuator.security;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.health.actuate.endpoint.HealthEndpoint;
import org.springframework.boot.security.autoconfigure.actuate.web.servlet.EndpointRequest;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import tools.jackson.databind.json.JsonMapper;

@SpringBootApplication
public class ActuatorSecurity {

    @Bean
    SecurityFilterChain actuatorChain(HttpSecurity http) throws Exception {
        http.securityMatcher(EndpointRequest.toAnyEndpoint())
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(EndpointRequest.to(HealthEndpoint.class)).permitAll()
                        .anyRequest().hasRole("OPS"))
                .httpBasic(Customizer.withDefaults());
        return http.build();
    }

    @Bean
    UserDetailsService users() {
        return new InMemoryUserDetailsManager(
                User.withUsername("ops").password("{noop}ops-secret").roles("OPS").build(),
                User.withUsername("dev").password("{noop}dev-secret").roles("DEV").build());
    }

    static final HttpClient HTTP = HttpClient.newHttpClient();

    static void get(int port, String path, String user) throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(
                URI.create("http://localhost:" + port + path));
        if (user != null) {
            String token = Base64.getEncoder().encodeToString(
                    (user + ":" + user + "-secret").getBytes(StandardCharsets.UTF_8));
            request.header("Authorization", "Basic " + token);
        }
        HttpResponse<String> response = HTTP.send(request.build(),
                HttpResponse.BodyHandlers.ofString());
        String body = response.statusCode() != 200 ? ""
                : path.contains("/env/") ? "property " + JsonMapper.shared()
                        .readTree(response.body()).get("property")
                : response.body();
        System.out.println((user == null ? "anonymous" : user) + " GET " + path + " -> "
                + response.statusCode() + " "
                + (body.length() > 70 ? body.substring(0, 70) + "..." : body));
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(ActuatorSecurity.class);
        app.setDefaultProperties(Map.of(
                "server.port", "0",
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "management.health.diskspace.enabled", "false",
                "management.health.ssl.enabled", "false",
                "management.endpoints.web.exposure.include", "health,env,loggers",
                "management.endpoint.health.show-details", "when-authorized",
                "management.endpoint.health.roles", "OPS",
                "management.endpoint.env.show-values", "when-authorized",
                "management.endpoint.env.roles", "OPS"));
        try (var context = app.run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            get(port, "/actuator/health", null);
            get(port, "/actuator/health", "ops");
            get(port, "/actuator/env/server.port", null);
            get(port, "/actuator/env/server.port", "dev");
            get(port, "/actuator/env/server.port", "ops");
        }
    }
}
Output
anonymous GET /actuator/health -> 200 {"groups":["liveness","readiness"],"status":"UP"}
ops GET /actuator/health -> 200 {"components":{"livenessState":{"status":"UP"},"ping":{"status":"UP"},...
anonymous GET /actuator/env/server.port -> 401 
dev GET /actuator/env/server.port -> 403 
ops GET /actuator/env/server.port -> 200 property {"source":"defaultProperties","value":"0"}
  • Anonymous callers got health with only the overall status. The ops user got the components too, because show-details=when-authorized with roles=OPS shows details only to that role.
  • env returned 401 without credentials and 403 for dev, who is authenticated but lacks the OPS role.
  • ops got 200 and the unmasked value 0, because show-values=when-authorized with the same role reveals values only to that role.

EndpointRequest lives in org.springframework.boot.security.autoconfigure.actuate.web.servlet in Spring Boot 4, and follows management.endpoints.web.base-path and the management port, so the rules stay correct if those change. The other programs on this page were run with Spring Security's auto-configuration excluded, which matches an application without Spring Security. Combine both protections in production: a management port that is not reachable from the internet, and authentication on it. The Spring Security page covers filter chains in depth.

Choosing what to expose

Common needs and the actuator settings that serve them
NeedSetting
Load balancer or Kubernetes probeshealth with the liveness and readiness groups; external checks only in readiness
A health view of one featuremanagement.endpoint.health.group.<name>.include
Which version is deployedinfo with build-info and git contributors
Metrics in a monitoring systemA Prometheus or OTLP registry, not the metrics endpoint
Debugging one instance in productionloggers, threaddump, env, behind authentication
Application-specific operationsA custom @Endpoint
Keeping endpoints off the public networkmanagement.server.port plus network rules
Secrets in env and configpropsKeep the default masking, or show-values=when-authorized with a role

Start with health and info exposed, add metrics export through a registry, and expose the debugging endpoints only behind a management port and a role. The configuration properties page explains the property sources env shows, and Spring Boot logging explains the levels loggers changes.