Blog
navigate_next
Java
SpringBoot Actuator
Gaurav Sharma
August 6, 2024

"Building production-grade web applications involves more than just writing code that works."

  • Complex Production Setups: In production, the environment is more complicated than on a developer's local machine. It involves things like multiple servers, databases, and different network settings, all while handling various levels of user activity. It’s not as easy to fix issues in this setup.
  • More Than Just Functionality: A production app needs to do more than just run. It has to be fast, able to handle lots of users at the same time, secure, and reliable. It’s important that the app not only works but also works well under different conditions.
  • Constant Monitoring: Unlike in development, where you can easily spot and fix problems, a production app needs to be constantly monitored. This means keeping track of its performance, checking for errors, and making sure everything is running smoothly for users all the time.

"Once an application is deployed, even a minor change in the code can potentially cause major issues."

  • Unintended Consequences: Code changes, even small ones, can have unintended side effects. For example, a minor update might introduce a bug that affects the application's performance, security, or functionality.
  • Dependencies and Integrations: Applications often rely on external systems, libraries, and services. A change in any part of the codebase could disrupt these dependencies, causing issues in the production environment.
  • User Impact: In a production setting, issues can directly impact end-users, leading to a poor user experience, loss of data, or even security breaches. This makes it crucial to catch and resolve problems as early as possible.

What is Spring Boot Actuator, and How Can It Help?

A Spring Boot sub-module, i.e., Spring Boot Actuator, offers significant advantages with minimal setup work. Developers and operations teams can see and control the behaviour of the application more effectively by integrating it. As a result, problems are easier to identify, diagnose, and fix before they become more serious, guaranteeing a more dependable and seamless user experience.

For every production-grade web application built with the Spring framework, the Spring Boot Actuator requirement must be given top priority.

Spring Boot Actuator provides a set of built-in endpoints that allow you to monitor and manage your Spring Boot application. These endpoints offer various insights into your application's health, metrics, and other operational data. Actuator endpoints can be accessed in two primary ways: HTTP and JMX. With HTTP, you can easily interact with the endpoints using a web browser or tools like cURL and Postman, making it convenient to check aspects such as your app's health or performance metrics. On the other hand, JMX is useful for Java environments, enabling integration with existing monitoring tools to delve deeper into the application's performance and configurations.

In this article, we will focus on using HTTP to interact with Spring Boot Actuator endpoints.

Features of Spring Boot Actuator

Spring Boot Actuator provides a range of features to monitor and manage production-grade applications. Here are the key functionalities it offers:

Endpoints

Actuator exposes various built-in endpoints that provide insights into different aspects of the application:

Most applications use HTTP endpoints, where the endpoint’s ID, prefixed with <span class="pink">/actuator</span>, is mapped to the base URL of the application. This means that you can access various management and monitoring features by appending the appropriate endpoint path to the base URL of your application, starting with <span class="pink">/actuator</span>. For example, if your base URL is <span class="pink">http://localhost:8080</span>, then the health endpoint would be accessible at <span class="pink">http://localhost:8080/actuator/health</span>.

  • /actuator/health: displays the health status of the application and its dependencies (e.g., databases, message brokers).
  • /actuator/metrics: provides detailed metrics about application performance, including response times, error rates, and resource usage.
  • /actuator/env: exposes properties from the application’s <span class="pink">ConfigurableEnvironment</span>, helping with debugging configuration issues.
  • /actuator/info: shows arbitrary application information, such as build details or custom metadata.
  • /actuator/loggers: allows viewing and modifying logging levels for various components.
  • /actuator/threaddump: generates a thread dump of the JVM, useful for diagnosing performance issues.
  • /actuator/mappings: lists all <span class="pink">@RequestMapping</span> paths in the application, assisting in understanding available API endpoints.
  • /actuator/scheduledtasks: displays scheduled tasks and their execution details.
  • /actuator/beans: provides a list of all spring beans in the application.

By default, Spring Boot Actuator provides only the <span class="pink">/health</span> endpoint. To expose additional endpoints, such as <span class="pink">/metrics</span>, <span class="pink">/beans</span>, and others, you need to explicitly enable them in your configuration.


management.endpoints.web.exposure.include=beans,metrics

💡 Custom Endpoints: It should be noted that we can design unique endpoints based on the needs of the application.

Metrics Collection

Metrics are measurements that help you understand how your application is performing. With Spring Boot Actuator, you can track different kinds of metrics to keep an eye on your application's health:

  • JVM Metrics:
    • Memory Usage: Shows how much memory the Java Virtual Machine (JVM) is using.
    • Garbage Collection: Tracks how often and how long garbage collection (cleaning up unused memory) takes.
    • Thread Counts: Counts the number of active threads in your application.
  • HTTP Metrics:
    • Request Counts: Counts how many HTTP requests your application is handling.
    • Response Times: Measures how long it takes to process these requests.
    • Status Codes: Shows the HTTP status codes returned by your application, like 200 (success) or 500 (error).
  • System Metrics:
    • CPU Usage: Tracks how much of the CPU is being used.
    • Disk Space: Shows how much disk space is available and used.
    • System Load: Measures how busy the system is.
  • Custom Metrics:
    • Application-Specific Metrics: Metrics you set up to track specific details relevant to your application, like how often a particular function is used.

Auditing

When you track and log significant events and actions in your program, including user logins, data modifications, or access to private areas, you are doing auditing.

For instance:

  • User Logins: Every time a user logs into your application, auditing records who logged in, when, and whether the login was successful or not.
  • Data Changes: Auditing can keep track of who, when, and what changes a user makes to data if they update or delete it.
  • Access to Sensitive Features: It tracks when users access or modify sensitive parts of the application, like admin settings.

💡 Spring Boot Actuator does not provide built-in auditing features directly. However, it can be integrated with other frameworks and tools, such as Spring Security for tracking security-related events, Spring Data JPA for auditing database operations, and custom solutions for more specific auditing needs. These integrations help in capturing and managing detailed records of application activities and changes.

Banner to that takes you to the latest version of the Unlogged plugin on the Jetbrains marketplace

Configuration and Security Management

Actuator allows you to access and manage application configuration details, such as environment properties and configuration properties, to help with debugging and ensuring proper setup. Actuator endpoi$nts can be secured to restrict access to sensitive information and operations. You can configure access control using Spring Security to ensure that only authorised users can access management features.

Note: In the following section of the article, we will go over these functionalities in more depth using code.

Building a RESTful Web Service with Spring Boot Actuator

This section will explain how to integrate Actuator into a Spring Boot-created RESTful web service and set significant endpoints, as well as how to use Actuator's features to obtain crucial insights into the performance, metrics, and health of your application. A Maven project will be utilised.

Visit start.spring.io to generate a Maven project with the following dependencies:

  • Spring Web
  • Spring Boot Actuator

Because Spring Boot Actuator is designed for managing and monitoring web applications, we've included the Spring Web dependency in our project. You can use any version of Java 17 or newer, as Spring Boot 3 requires at least Java 17.

Spring Initializr setup page for creating a new Spring Boot project with selected dependencies: Spring Web for building RESTful applications and Spring Boot Actuator for monitoring and managing the application.

Spring Boot actuator dependency.


<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

As soon as we start the application without any additional code or configuration, the console displays "Exposing one endpoint beneath base path/actuator." This message indicates that the <span class="pink">/actuator/health</span> endpoint, which provides basic health information about the application, is by default enabled.

Console log showing the startup of the ActuatorDemoApplication with Spring Boot version 3.3.2. The application initializes the Tomcat web server on port 8080 and exposes an endpoint at the base path /actuator for monitoring and management tasks.

accessing the endpoint: http://localhost:8080/actuator

By default, you will only get these end points, and these end points are hyperlinks.

JSON response from `http://localhost:8080/actuator` endpoint, showing links to the `self`, `health`, and `health-path` endpoints. These provide access to various monitoring and health-check options for the Spring Boot application.

In order to obtain endpoints only associated with metrics, info or other related data, it is necessary to manually specify them in the application.properties file.

	
management.endpoints.web.exposure.include=beans,health,info,metrics

JSON response displaying available actuator endpoints in a Spring Boot application, including links for beans, health, info, and metrics, among others.

Or

After adding <span class="pink">management.endpoints.web.exposure.include=*</span> to the <span class="pink">application.properties</span> file and accessing the endpoint at <span class="pink">http://localhost:8080/actuator</span>, you will see all the available Actuator endpoints on a hypermedia web page.

But don’t you worry. no one is going to use all these end points in an application. only a handful, so enable only what is required for your project.

	
{
"_links": {
"self": {
"href": "http://localhost:8080/actuator",
"templated": false
},
"beans": {
"href": "http://localhost:8080/actuator/beans",
"templated": false
},
"caches-cache": {
"href": "http://localhost:8080/actuator/caches/{cache}",
"templated": true
},
"caches": {
"href": "http://localhost:8080/actuator/caches",
"templated": false
},
"health-path": {
"href": "http://localhost:8080/actuator/health/{*path}",
"templated": true
},
"health": {
"href": "http://localhost:8080/actuator/health",
"templated": false
},
"info": {
"href": "http://localhost:8080/actuator/info",
"templated": false
},
"conditions": {
"href": "http://localhost:8080/actuator/conditions",
"templated": false
},
"configprops": {
"href": "http://localhost:8080/actuator/configprops",
"templated": false
},
"configprops-prefix": {
"href": "http://localhost:8080/actuator/configprops/{prefix}",
"templated": true
},
"env": {
"href": "http://localhost:8080/actuator/env",
"templated": false
},
"env-toMatch": {
"href": "http://localhost:8080/actuator/env/{toMatch}",
"templated": true
},
"loggers": {
"href": "http://localhost:8080/actuator/loggers",
"templated": false
},
"loggers-name": {
"href": "http://localhost:8080/actuator/loggers/{name}",
"templated": true
},
"heapdump": {
"href": "http://localhost:8080/actuator/heapdump",
"templated": false
},
"threaddump": {
"href": "http://localhost:8080/actuator/threaddump",
"templated": false
},
"metrics-requiredMetricName": {
"href": "http://localhost:8080/actuator/metrics/{requiredMetricName}",
"templated": true
},
"metrics": {
"href": "http://localhost:8080/actuator/metrics",
"templated": false
},
"sbom": {
"href": "http://localhost:8080/actuator/sbom",
"templated": false
},
"sbom-id": {
"href": "http://localhost:8080/actuator/sbom/{id}",
"templated": true
},
"scheduledtasks": {
"href": "http://localhost:8080/actuator/scheduledtasks",
"templated": false
},
"mappings": {
"href": "http://localhost:8080/actuator/mappings",
"templated": false
}
}
}

Banner to that takes you to the latest version of the Unlogged plugin on the Jetbrains marketplace

Discussing a few endpoints in detail:

/actuator/health

JSON response from the Spring Boot Actuator health endpoint indicating the status as "UP".

“status”: “UP” means the application is healthy and running smoothly without any issues.

To view detailed health information about your application, you have to add an extra configuration in your application.properties file, i.e.,

<span class="pink">management.endpoint.health.show-details=always</span>

	
{
"status": "UP",
"components": {
"diskSpace": {
"status": "UP",
"details": {
"total": 203286376448,
"free": 197754081280,
"threshold": 10485760,
"path": "D:\\actuatorDemo\\.",
"exists": true
}
},
"ping": {
"status": "UP"
}
}
}

explanation:

Now, when we access <span class="pink">/actuator/health</span> endpoint, we get a detailed health report about our application. The <span class="pink">"status": "UP"</span> at the top level signifies that the application is currently running smoothly without any critical issues. The <span class="pink">"components"</span> field contains detailed information about various subsystems:

  1. diskSpace: Reports the status of the disk storage where the application is deployed. It shows:
    • <span class="pink">"status": "UP"</span>: The disk space is sufficient and accessible.
    • <span class="pink">"total"</span>: The total disk space available (203,286,376,448 bytes).
    • <span class="pink">"free"</span>: The available free space (197,754,081,280 bytes).
    • <span class="pink">"threshold"</span>: The minimum amount of free space required (10,485,760 bytes).
    • <span class="pink">"path"</span>: The disk path being monitored ("D:\\actuatorDemo\\.").
    • <span class="pink">"exists"</span>: Confirms that the specified disk path exists.
  2. ping: A simple check that confirms the application can respond to a ping request, with <span class="pink">"status": "UP"</span> indicating responsiveness.

/actuator/beans

This endpoint shows all the beans currently present in the Spring ApplicationContext, providing detailed information about each bean, including its name, type, scope, and the dependencies it relies on.

We'll create a component class, retrieve it as a bean from the application context, and then examine its details.

CustomBean.java

	
package com.unlogged.custom;

import org.springframework.stereotype.Component;

@Component
public class CustomBean {
    private String message;

    public CustomBean() {
        this.message = "Hello from CustomBean!";
    }

    public String getMessage() {
        return message;
    }
}

retrieving the bean of the CustomBean class from the application context:

	
package com.unlogged;

import com.unlogged.custom.CustomBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class ActuatorDemoApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(ActuatorDemoApplication.class, args);

        CustomBean customBean = context.getBean(CustomBean.class);
    }

}

explanation: In this code, we retrieve the CustomBean from the ApplicationContext using getBean() method.

When we access the bean endpoint at <span class="pink">http://localhost:8080/actuator/beans</span>, we can find our custom bean listed there.

explanation:

This output shows:

  • The bean name (customBean)
  • Its scope (singleton)
  • The full class name
  • The resource location
  • Any dependencies (none in this case)

/actuator/info

The <span class="pink">actuator/info</span> endpoint provides custom information about the Spring Boot application. It can display details like the app's version, description, and build information. This endpoint helps users quickly understand key aspects of the application's deployment and versioning.

At first, by default, accessing the info endpoint:

Empty JSON response from the Spring Boot Actuator info endpoint at /actuator/info.

we have to configure a little our application.properties file to get the desired information:

	
#info configuration
info.app.name=Actuator Demo for Unlogged
info.app.version=1.0.0
info.app.description=Writing an article on Spring Boot actuator for Unlogged
info.app.author.name=Gaurav
management.info.env.enabled=true
management.info.java.enabled=true
management.info.os.enabled=true

explanation:

This setup adds details like the app's name, version, description, author, and system information such as Java or operating system info to the <span class="pink">/info</span> endpoint in Spring Boot.

Now accessing <span class="pink">http://localhost:8080/actuator/info</span>:

It provides information on my computer's Java setup, the operating system, the app name, version, description, author, and more.


{
"app": {
"name": "Actuator Demo for Unlogged",
"version": "1.0.0",
"description": "Writing an article on Spring Boot actuator for Unlogged",
"author": {
"name": "Gaurav"
}
},
"java": {
"version": "21.0.2",
"vendor": {
"name": "Oracle Corporation"
},
"runtime": {
"name": "Java(TM) SE Runtime Environment",
"version": "21.0.2+13-LTS-58"
},
"jvm": {
"name": "Java HotSpot(TM) 64-Bit Server VM",
"vendor": "Oracle Corporation",
"version": "21.0.2+13-LTS-58"
}
},
"os": {
"name": "Windows 11",
"version": "10.0",
"arch": "amd64"
}
}

/actuator/mappings

The <span class="pink">/actuator/mappings</span> endpoint shows all the different web addresses your app can respond to and which parts of your code handle them. It's like a list that tells you, "If someone goes to this URL, this is the part of the app that gets triggered."

We will do some hands-on coding and create a rest controller in our project’s base package named :

AcutatorController.java


package com.unlogged.controller;

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

@RestController
@RequestMapping("/api")
public class ActuatorController {

    @GetMapping("/greeting")
    public String greeting() {
        return "Hello, Everyone! Happy Coding!";
    }
}

Along with our custom mapping, such as <span class="pink">api/greeting</span>, this URL, <span class="pink">http://localhost:8080/actuator/mappings</span> , displays a number of default actuator mappings.

The api information, namely <span class="pink">/api/greeting</span>, is displayed in full in the image below. It’s very helpful to debug when you are getting an error in any API; you can check the full details of that api through mappings.

Information about a handler method in Spring Boot, specifying the GET request for the "/api/greeting" endpoint managed by "ActuatorController" with details on the method and request mapping conditions.

/actuator/metrics

The <span class="pink">/actuator/metrics</span> endpoint in Spring Boot Actuator offers a tonne of valuable insights into your application's performance and resource utilisation. Imagine it as a dashboard that provides you with a comprehensive overview of different metrics, including memory usage, CPU load, and request statistics.

When you access this endpoint, you'll see a list of available metrics, like <span class="pink">jvm.memory.used</span> or <span class="pink">system.cpu.usage</span>. Each metric is like a sensor that tells you about a specific aspect of your application's environment. For example, <span class="pink">jvm.memory.used</span> indicates how much memory your Java Virtual Machine (JVM) is currently using, while <span class="pink">system.cpu.usage</span> shows the percentage of CPU being used by the system.

These metrics are incredibly useful for monitoring and diagnosing issues. If your application starts slowing down, you can check the <span class="pink">/actuator/metrics</span> endpoint to see if you're running low on memory or if the CPU is being overutilised. This helps you make informed decisions about scaling your application or optimising your code.

Accessing the metrics endpoint at: <span class="pink">http://localhost:8080/actuator/metrics</span>


{
"names": [
"application.ready.time",
"application.started.time",
"disk.free",
"disk.total",
"executor.active",
"executor.completed",
"executor.pool.core",
"executor.pool.max",
"executor.pool.size",
"executor.queue.remaining",
"executor.queued",
"http.server.requests",
"http.server.requests.active",
"jvm.buffer.count",
"jvm.buffer.memory.used",
"jvm.buffer.total.capacity",
"jvm.classes.loaded",
"jvm.classes.unloaded",
"jvm.compilation.time",
"jvm.gc.live.data.size",
"jvm.gc.max.data.size",
"jvm.gc.memory.allocated",
"jvm.gc.memory.promoted",
"jvm.gc.overhead",
"jvm.info",
"jvm.memory.committed",
"jvm.memory.max",
"jvm.memory.usage.after.gc",
"jvm.memory.used",
"jvm.threads.daemon",
"jvm.threads.live",
"jvm.threads.peak",
"jvm.threads.started",
"jvm.threads.states",
"logback.events",
"process.cpu.time",
"process.cpu.usage",
"process.start.time",
"process.uptime",
"system.cpu.count",
"system.cpu.usage",
"tomcat.sessions.active.current",
"tomcat.sessions.active.max",
"tomcat.sessions.alive.max",
"tomcat.sessions.created",
"tomcat.sessions.expired",
"tomcat.sessions.rejected"
]
}

explanation:

This is a list of key metrics you can check using Spring Boot Actuator's <span class="pink">/actuator/metrics</span> endpoint. Here's a quick rundown:

  1. App Startup: <span class="pink">application.ready.time</span> and <span class="pink">application.started.time</span> shows how long it takes for your app to get going.
  2. Disk Space: <span class="pink">disk.free and disk.total</span> tell you how much disk space you have left and overall.
  3. Thread Pools: Metrics like <span class="pink">executor.active, executor.pool.size</span>, and <span class="pink">executor.queue.remaining</span> show how busy your thread pools are.
  4. JVM Stuff: Includes memory usage (<span class="pink">jvm.memory.used</span>), garbage collection data (<span class="pink">jvm.gc.memory.allocated</span>), and thread counts (<span class="pink">jvm.threads.live</span>).
  5. Logs: <span class="pink">logback.events</span> counts the log events.
  6. CPU & Process: <span class="pink">process.cpu.time</span> and <span class="pink">process.cpu.usage</span> show how much CPU your app is using, plus process uptime.
  7. System Info: <span class="pink">system.cpu.count</span> and <span class="pink">system.cpu.usage</span> give an overview of your CPU's capacity and usage.
  8. Tomcat Sessions: Metrics like <span class="pink">tomcat.sessions.active.current</span> and <span class="pink">tomcat.sessions.created</span> track session activity on the Tomcat server.

example:

You can access any of these metrics directly. For instance, if you want to check the live JVM threads, simply hit the URL: <span class="pink">http://localhost:8080/actuator/metrics/jvm.threads.live</span>.

JSON response from the "/actuator/metrics/jvm.threads.live" endpoint in Spring Boot, displaying the current count of live JVM threads.

explanation:

The metric <span class="pink">jvm.threads.live</span> indicates that there are currently 25 live threads, including both daemon and non-daemon threads, in the JVM.

Note: Just a heads up: we have got a bunch of Actuator endpoints that give you all sorts of cool info for managing and monitoring your app. We can not go over all of them here, but feel free to check them out on your own to get a better grasp.Once you finish reading this article, you will be all set to use Actuator like a pro.

Creating a custom actuator endpoint

You can use the built-in ends that come with the Spring Boot Actuator, but sometimes you need something different. You might want to share the most recent statistics from your app or show what is going on with a custom file.

To make a custom endpoint, you must first define a class that is marked with <span class="pink">@Endpoint</span>. Then, based on what you want your endpoint to do (read data, change state, or delete something), you will add methods that are marked with <span class="pink">@ReadOperation</span>, <span class="pink">@WriteOperation</span>, or <span class="pink">@DeleteOperation</span>.

For example, a simple read-only (@ReadOperation) endpoint might look like this:

CustomEndPoint.java

	
   package com.unlogged.custom;

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

import java.util.HashMap;
import java.util.Map;

@Endpoint(id = "customEndpoint")
@Component
public class CustomEndPoint {

    private final Map<String, String> dataStore = new HashMap<>();

    @ReadOperation
    public Map<String, String> customInfo() {
        Map<String, String> response = new HashMap<>();
        response.put("status", "Custom endpoint is up and running");
        response.putAll(dataStore);
        return response;
    }
}

explanation:

We’ve set up a custom Actuator endpoint named <span class="pink">customEndpoint</span> to manage and view app data.

Read Operation: The <span class="pink">customInfo()</span> method is triggered when you access <span class="pink">/actuator/customEndpoint</span>

through the browser, make a GET request from Postman or any other tool.

So, accessing <span class="pink">http://localhost:8080/actuator/customEndpoint</span> will display a status message.

Custom endpoint at `/actuator/customEndpoint` showing a JSON response with status "Custom endpoint is up and running".

Similarly, for write operations (@WriteOperation), we have implemented a method:


    @WriteOperation
    public String updateInfo(String key, String value) {
        // Update data in the store
        dataStore.put(key, value);
        return "Updated key '" + key + "' with value '" + value + "'";
    }

To write data using Postman:

  1. Set the request method to POST.
  2. Use the URL: <span class="pink">http://localhost:8080/actuator/customEndpoint</span>.
  3. In the Headers section, set the <span class="pink">Content-Type</span> to <span class="pink">application/json</span>.
  4. Provide the data to be written in the request body.

This setup allows you to add new data to your application through the custom endpoint.

Postman request to the `/actuator/customEndpoint` with a JSON body containing `key` as "1" and `value` as "Gaurav", and a response confirming the update of key "1" with value "Gaurav".

When you access <span class="pink">http://localhost:8080/actuator/customEndpoint</span> through the browser, you'll see the data that was previously added, along with a status message.

Response from the /actuator/customEndpoint showing JSON output with "1": "Gaurav" and "status": "Custom endpoint is up and running".

Securing actuator endpoints

Spring Boot Actuator endpoints provide valuable insights into the internals of our application, offering crucial information for monitoring, management, and troubleshooting. However, this wealth of information can be a double-edged sword. If left unsecured, these endpoints could potentially expose sensitive data or provide attackers with critical information about the system and application.

Step 1: Begin by adding the Spring Security dependency to the <span class="pink">pom.xml</span> file.

	
<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>

Step 2: Create a <span class="pink">config</span> package and, within it, add a <span class="pink">SecurityConfig</span> class. This class will be used to define our security configuration.

<span class="pink">SecurityConfig.java</span>


package com.unlogged.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(requests -> requests
                        .requestMatchers("/actuator/**").authenticated()
                        .anyRequest().permitAll()
                )
                .httpBasic(Customizer.withDefaults())
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .build();
    }
}

explanation:

The securityFilterChain method configures Spring Security for a web application. It:

  1. Disables CSRF protection
  2. Sets up authorization rules:
    • Requires authentication for "<span class="pink">/actuator/**</span>" endpoints
    • Allows all other requests without authentication
  3. Enables HTTP Basic authentication
  4. Configures stateless session management

Step3: setting username and password in <span class="pink">application.properties</span> file:

	
spring.security.user.name=gaurav
spring.security.user.password=12345

Note: This is not the standard method for setting up usernames and passwords. Implementing a fully customizable user registration and login system is a complex topic that requires more in-depth discussion, which we won't cover here. Our primary focus is on securing the Actuator endpoints.Spring Security is a highly customizable module, so you can tailor the security configurations as needed.

Demo: Testing our secured endpoint

Basic Intro: Integrating External Tools like Prometheus and Grafana with Spring Boot Actuator

Spring Boot Actuator is great for basic monitoring, but integrating it with tools like Prometheus and Grafana takes things to the next level. These external tools offer more advanced features that developers and ops teams really need.

With Prometheus and Grafana, you get deeper insights into your app's performance. They show you detailed metrics over time, not just snapshots. This helps you spot trends and potential issues before they become real problems.

These tools also make it easier to visualize data. Instead of raw numbers, you get graphs and charts that quickly show what's going on. This is super helpful when you're trying to figure out why your app might be slowing down or using too much memory.

Another big plus is the alerting system. You can set up alerts to ping you when something's not right, so you don't have to constantly watch your app.

For teams running multiple services, these tools are a game-changer. You can monitor all your apps from one place, which saves a ton of time and makes it easier to see how different parts of your system are working together.

💡 We'll delve into integrating Prometheus, Grafana, and other tools in separate articles, as this topic is too extensive to cover comprehensively in a single piece. While Spring Boot Actuator is a broad subject and can't be fully covered in one article, this piece should be more than sufficient to get you started and running. If you find any aspects particularly interesting, feel free to explore them further.

Cheers!

Happy Coding.

Gaurav Sharma
August 6, 2024
Use Unlogged to
mock instantly
record and replay methods
mock instantly
Install Plugin