Sub topic 13
Creating a custom Actuator endpoint
Built-in endpoints cover health, metrics, loggers and mappings. Sometimes you need something specific to your application, such as a view of feature flags, a cache status report, or an operation that drains a queue before a deployment. Actuator lets you write your own endpoint and gives you the same exposure, security and technology-neutral behavior as the built-in ones.
This chapter assumes you know how endpoints are exposed and secured (earlier chapters), and that you are comfortable with Spring beans and basic JSON over HTTP. The examples target Spring Boot 3.
What an endpoint is
An Actuator endpoint is a Spring bean annotated with @Endpoint. Its methods are operations. Actuator discovers the bean and adapts it to each technology you expose it through. Today that means HTTP (Spring MVC, WebFlux or Jersey) and JMX.
Because the endpoint is written once, you do not write a controller. You declare operations, and Actuator maps them for you.
| Annotation | Purpose | HTTP mapping |
|---|---|---|
| `@Endpoint` | Marks the bean and sets its `id` | `/actuator/{id}` |
| `@ReadOperation` | Returns data | `GET` |
| `@WriteOperation` | Changes state | `POST` |
| `@DeleteOperation` | Removes state | `DELETE` |
| `@Selector` | Marks a parameter as part of the path | Path segment |
The id becomes the URL segment and the key in the exposure list. Use lowercase letters and digits, starting with a letter. Names such as features or cacheStats work, but a plain lowercase id is the safest.
A first endpoint
This endpoint stores feature flags in memory. It has one read operation and one write operation.
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
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.stereotype.Component;
@Component
@Endpoint(id = "features")
public class FeaturesEndpoint {
private final Map<String, Boolean> features = new ConcurrentHashMap<>();
@ReadOperation
public Map<String, Boolean> features() {
return features;
}
@WriteOperation
public void configure(@Selector String name, boolean enabled) {
features.put(name, enabled);
}
}The bean is not reachable yet. A custom endpoint follows the same exposure rules as built-in ones, so add its id to the list:
management:
endpoints:
web:
exposure:
include: health,info,featuresStart the application and call it:
curl http://localhost:8080/actuator/features
curl -X POST http://localhost:8080/actuator/features/dark-mode \
-H "Content-Type: application/json" \
-d '{"enabled": true}'
curl http://localhost:8080/actuator/featuresThe first call returns {}. The POST returns 204 No Content because the method returns void. The last call returns {"dark-mode":true}.
How parameters are bound
Parameter binding is the part that surprises most people, because there are no @PathVariable or @RequestBody annotations here.
- A parameter annotated with
@Selectoris taken from the path. In the example,/actuator/features/dark-modebindsnametodark-mode. - Every other parameter of a write operation is read from the JSON request body, by parameter name. This is why the body is
{"enabled": true}and not justtrue. - Every other parameter of a read operation is read from the query string.
- Values are converted to the parameter type, so
"true"becomes aboolean. - A parameter is required unless it is annotated
@Nullable. A missing required parameter produces400 Bad Request.
Binding by name depends on the compiler keeping parameter names. A Maven or Gradle build using the Spring Boot plugins sets -parameters for you. If you build with plain javac and see parameter binding errors, add that flag.
A selector captures a single path segment by default. To capture the rest of the path, use @Selector(match = Selector.Match.ALL_REMAINING) with a String[] parameter.
Adding a single-item read and a delete
Operations of the same kind can coexist when their selectors differ. This version adds a per-flag lookup and a delete.
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.boot.actuate.endpoint.annotation.DeleteOperation;
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.stereotype.Component;
@Component
@Endpoint(id = "features")
public class FeaturesEndpoint {
private final Map<String, Boolean> features = new ConcurrentHashMap<>();
@ReadOperation
public Map<String, Boolean> features() {
return features;
}
@ReadOperation
public Boolean feature(@Selector String name) {
return features.get(name);
}
@WriteOperation
public void configure(@Selector String name, boolean enabled) {
features.put(name, enabled);
}
@DeleteOperation
public void delete(@Selector String name) {
features.remove(name);
}
}Over HTTP, a read operation that returns null produces 404 Not Found. This is how GET /actuator/features/unknown reports a missing flag without extra code. Write and delete operations that return null or void produce 204.
The return value is serialized with the application's ObjectMapper, so records and simple POJOs work. Return a small, stable structure. Anything you return becomes part of an operational contract that scripts and dashboards may depend on.
Request flow
Restricting a technology
@Endpoint is technology-neutral. If an operation only makes sense for one technology, use a narrower annotation:
@WebEndpointcreates an endpoint that exists only over HTTP.@JmxEndpointcreates an endpoint that exists only over JMX.@EndpointWebExtensionadds HTTP-specific behavior to an existing endpoint, for example to return aWebEndpointResponsewith a custom status code.
Prefer plain @Endpoint unless you have a reason. A neutral endpoint is available over JMX for free, which some operations teams rely on.
If you need a specific status code, return a WebEndpointResponse<T> from a web endpoint or extension:
import java.util.Map;
import org.springframework.boot.actuate.endpoint.web.WebEndpointResponse;
import org.springframework.boot.actuate.endpoint.web.annotation.WebEndpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.Selector;
import org.springframework.stereotype.Component;
@Component
@WebEndpoint(id = "flagstatus")
public class FlagStatusEndpoint {
private final Map<String, Boolean> flags = Map.of("beta", true);
@ReadOperation
public WebEndpointResponse<Boolean> flag(@Selector String name) {
Boolean value = flags.get(name);
if (value == null) {
return new WebEndpointResponse<>(WebEndpointResponse.STATUS_NOT_FOUND);
}
return new WebEndpointResponse<>(value, WebEndpointResponse.STATUS_OK);
}
}Securing and controlling access
A custom endpoint is protected like any other. Three points matter.
- Exposure is opt-in. If the id is not in
management.endpoints.web.exposure.include, the endpoint is not served over HTTP, even though the bean exists. - Matchers work by id. The
EndpointRequest.to("features")andEndpointRequest.toAnyEndpoint()matchers from the securing chapter pick up your endpoint automatically. If you usedanyRequest().hasRole("ACTUATOR"), your endpoint is already covered. - Write operations are POST and DELETE requests. Spring Security enables CSRF protection for these by default. A script that sends a valid Basic credential can still get
403. For a machine-to-machine management chain, disable CSRF for Actuator requests deliberately and only on that chain, or have clients send a CSRF token.
You can also restrict what an endpoint is allowed to do without touching security rules. In Spring Boot 3.4 and later, set management.endpoint.features.access to none, read-only or unrestricted. With read-only, the write and delete operations are not served. Earlier versions use management.endpoint.features.enabled=false to switch the whole endpoint off. Check the documentation for your version before relying on either property.
Testing the endpoint
Because the endpoint is a plain Java class, a unit test needs no Spring context:
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
class FeaturesEndpointTest {
@Test
void configureStoresFlagAndDeleteRemovesIt() {
FeaturesEndpoint endpoint = new FeaturesEndpoint();
endpoint.configure("dark-mode", true);
assertEquals(true, endpoint.feature("dark-mode"));
endpoint.delete("dark-mode");
assertNull(endpoint.feature("dark-mode"));
}
}This test covers the logic. It does not cover the HTTP mapping, exposure or security. Check those with @SpringBootTest and MockMvc (setting the exposure property in the test), or by calling a running instance with curl.
Common errors
- 404 on the endpoint URL. The id is missing from the exposure list, or the bean is not a Spring bean. Check that the class is annotated
@Component(or declared with@Bean) and that the id is listed. - 400 on a POST. A required parameter is missing from the JSON body, or the body is not sent with
Content-Type: application/json. - 403 on a POST with correct credentials. CSRF protection is rejecting the request.
- Parameter names not found. The class was compiled without
-parameters. - State lost on restart or inconsistent across instances. An in-memory map belongs to a single JVM. For real feature flags in a multi-instance deployment, an endpoint should read from and write to shared storage, or only expose it for diagnostics.
- Slow read operations. Monitoring tools may call an endpoint often. Keep read operations fast and free of side effects.
Exercise
You add a @Component @Endpoint(id = "cachestats") bean with one @ReadOperation method, but GET /actuator/cachestats returns 404. Name two likely causes, and say which setting you would change for the first.
Show answer
The id cachestats is probably not in management.endpoints.web.exposure.include, so change that property to list it (for example health,info,cachestats). Another likely cause is that the class is not registered as a Spring bean, for example if it lacks @Component or sits outside the scanned packages. The endpoint could also be switched off or restricted through its access or enabled property.
Exercise
A @WriteOperation method is declared as void configure(@Selector String name, boolean enabled). What URL, HTTP method and body does a client use to enable the flag beta, and what status does it get back on success?
Show answer
It sends POST /actuator/features/beta with Content-Type: application/json and the body {"enabled": true}. The selector name comes from the path, and enabled comes from the JSON body. Because the method returns void, the response is 204 No Content.