Spring Boot Actuator - Application Health Checks and Monitoring Support

An explanation of Spring Boot Actuator and creation of an example project.

Overview

This article looks at the built-in HTTP endpoints that can be used in a Boot application for various monitoring and management purposes. Before Spring Boot, if you needed to introduce this type of monitoring feature into an application, you had to manually develop all of these components, even though they were often essential. However, Spring Boot has an Actuator module that makes monitoring features very easy to create.

With only a few configuration settings, you can easily use all management and monitoring-related information. This article explains how to configure Spring Boot 2 Actuator endpoints.

Spring Boot Actuator Module

With the Spring Boot module, you can monitor and manage application usage in an operating environment without writing Actuator code or configuration. This monitoring and management information is exposed through REST-style endpoint URLs.

Actuator Dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
}

Important Actuator Endpoints

Most applications expose endpoints through HTTP, where the endpoint ID is mapped to a URL with the /actuator prefix. For example, the health endpoint is mapped to /actuator/health by default.

Important and commonly used Actuator endpoints are as follows.

Endpoint Description
/auditevents Returns all auto-configuration candidates and why each candidate was applied or not applied.
/beans Returns a complete list of all Spring beans in the application.
/mappings Returns a combined list of all @RequestMapping. paths.
/env Returns the list of properties in the current environment.
/health Returns application health information.
/caches Returns available caches.
/conditions Returns the conditions evaluated in configuration and auto-configuration.
/configprops Returns all @ConfigurationProperties.
/Intergrationgraph Shows the Spring Integration graph. It requires a dependency on spring-intergration-core.
/loggers Logger configuration for the application.
/scheduledtasks Returns scheduled tasks in the application.
/sessions Displays trace logs, by default the last 100 HTTP requests. An HttpTraceRepository Bean is required.
/httptrace Can retrieve and delete user sessions from the Spring Session-backed session store. A Servlet-based web application using Spring Session is required.
/shutdown Can gracefully shut down the application. It is disabled by default.
/threaddump Performs a thread dump.
/metrics Shows useful metric information such as JVM memory usage, system CPU usage, and open files.

Spring web applications, such as Spring MVC, Spring WebFlux, or Jersey, provide the following additional endpoints.

Endpoint Description
/heapdump Returns an hprof heap dump file.
/logfile Displays the contents of the log file if the logging.file.name or logging.file.path property is configured.

Endpoint Security

By default, if Spring Security is available on the classpath, it is enabled for all Actuator endpoints.

For example, to configure custom security for HTTP endpoints so that only users with a specific role can access them, configure WebSecurityConfigurerAdapter as follows.

@Configuration(proxyBeanMethods = false)
public class ActuatorSecurity extends WebSecurityConfigurerAdapter {
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests((requests) ->
                requests.anyRequest().hasRole("ENDPOINT_ADMIN"));
        http.httpBasic();
    }
 
}

The configuration above allows only users with the ENDPOINT_ADMIN role to access active endpoints.

Enable Endpoints

By default, all endpoints except /shutdown are enabled. To disable all endpoints, set the property as follows.

management.endpoints.enabled-by-default=false

Then enable the endpoints you want the application to use with the management.endpoint.{id}.enabled. pattern.

management.endpoint.health.enabled=true
management.endpoint.loggers.enabled=true

CORS Support

CORS support is disabled by default and is enabled only when the .management.endpoints.cors.allowed-origins property is configured.

management.endpoints.web.cors.allowed-origins=https://example.com
management.endpoints.web.cors.allowed-methods=GET,POST

Here, the management context path is /management.

Response Caching

Actuator endpoints automatically cache responses for read operations that do not use parameters. The cache.time-to-live property is used to set how long an endpoint caches a response.

management.endpoint.beans.cache.time-to-live=20s

Create a Spring Boot Actuator Project

Now create a simple Spring Boot application example project. With this example, you can access Actuator endpoints and inspect the details.

New Project Creation Command

Create a new Spring Boot project with the following curl command.

curl https://start.spring.io/starter.tgz \
-d bootVersion=2.7.6 \
-d dependencies=web,actuator \
-d baseDir=spring-actuator \
-d groupId=com.devkuma \
-d artifactId=spring-actuator \
-d packageName=com.devkuma.actuator \
-d applicationName=ActuatorApplication \
-d javaVersion=11 \
-d packaging=jar \
-d type=gradle-project | tar -xzvf -

This command uses Java 11, Gradle, Spring Boot 2.7.6, and adds “web,actuator” as dependencies.

Add a Simple REST Endpoint

Now add one simple REST endpoint, /hello, to the application.

package com.devkuma.actuator;

import java.util.Date;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloRestController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello User !! " + new Date();
    }
}

Configure Exposure of All Endpoints

Add the following setting to the configuration file (application.properties) to expose all endpoints through the Web API.

management.endpoints.web.exposure.include=*

Start Spring Boot Actuator

Now start the project.

Endpoint Environment Output

  • http://localhost:8080/actuator/env
  • This URL provides all environment configuration details for the server.
{
    "activeProfiles": [],
    "propertySources": [
        {
            "name": "server.ports",
            "properties": {
                "local.server.port": {
                    "value": 8080
                }
            }
        },
        {
            "name": "servletContextInitParams",
            "properties": {}
        },
        {
            "name": "systemProperties",
            "properties": {
                "gopherProxySet": {
                    "value": "false"
                },
                "awt.toolkit": {
                    "value": "sun.lwawt.macosx.LWCToolkit"
                },
                "java.specification.version": {
                    "value": "11"
                },
                "sun.cpu.isalist": {
                    "value": ""
                },

... omitted ...

Endpoint Bean Output

  • http://localhost:8080/actuator/beans
  • This URL provides the list of all Spring beans loaded in the context.
{
    "contexts": {
        "application": {
            "beans": {
                "endpointCachingOperationInvokerAdvisor": {
                    "aliases": [],
                    "scope": "singleton",
                    "type": "org.springframework.boot.actuate.endpoint.invoker.cache.CachingOperationInvokerAdvisor",
                    "resource": "class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/EndpointAutoConfiguration.class]",
                    "dependencies": [
                        "org.springframework.boot.actuate.autoconfigure.endpoint.EndpointAutoConfiguration",
                        "environment"
                    ]
                },
                "defaultServletHandlerMapping": {
                    "aliases": [],
                    "scope": "singleton",
                    "type": "org.springframework.web.servlet.HandlerMapping",
                    "resource": "class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]",
                    "dependencies": [
                        "org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration"
                    ]
                },

... omitted ...

Endpoint Thread Dump Output

  • http://localhost:8080/actuator/threaddump
  • This URL provides the current server thread dump.
{
    "threads": [
        {
            "threadName": "Reference Handler",
            "threadId": 2,
            "blockedTime": -1,
            "blockedCount": 5,
            "waitedTime": -1,
            "waitedCount": 0,
            "lockName": null,
            "lockOwnerId": -1,
            "lockOwnerName": null,
            "daemon": true,
            "inNative": false,
            "suspended": false,
            "threadState": "RUNNABLE",
            "priority": 10,
            "stackTrace": [
                {
                    "classLoaderName": null,
                    "moduleName": "java.base",
                    "moduleVersion": "11.0.16.1",
                    "methodName": "waitForReferencePendingList",
                    "fileName": "Reference.java",
                    "lineNumber": -2,
                    "className": "java.lang.ref.Reference",
                    "nativeMethod": true
                },

... omitted ...

These endpoints provide standard information in a browser. This article introduced a few basic important endpoints that are commonly referenced, but Spring Boot provides many more endpoints as mentioned in this link.

Advanced Actuator Configuration Options

Change the Management Endpoint Context Path

By default, all endpoints are provided under the application’s base context path starting with /actuator. If, for some reason, your application already has endpoints that start with /actuator, you can change the base path to something else.

Simply specify the new base path in application.properties.

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

Now you can access all Actuator endpoints with the new URL. For example:

  • /manage/health
  • /manage/dump
  • /manage/env
  • /manage/beans

Change the Management Server Port

To change the port for management endpoints, add this entry to the application.properties configuration file.

management.server.port=8081

Summary

In this Spring Boot Actuator project example, we learned how to configure management and monitoring endpoints with a few simple settings.
When creating a project, if you need to add application health checks or monitoring support, it is worth considering introducing Spring Actuator.

References

  • The completed project code above has been uploaded here.