🌟 Day 6: My Spring Boot Learning Journey 🌟

🌟 Day 6: My Spring Boot Learning Journey 🌟

Today's session was all about exploring tools and features that enhance development and monitoring in Spring Boot. Here's what I covered:

1️⃣ Spring Boot Starter Actuator

  • Spring Boot Actuator is a sub-project of the Spring Boot framework that provides production-ready features for monitoring and managing Spring Boot applications.

  • It offers a set of built-in endpoints that allow developers to monitor and interact with their applications in real time.

  • The Spring Boot Actuator introduces the concept of "actuator endpoints." These endpoints are pre-defined URLs that expose various operational information about the running application.

  • By accessing these endpoints, developers can retrieve data such as health status, metrics, configuration properties, and more.

Let's see some of the commonly used actuator endpoints:

1. : Provides health information about the application, indicating whether it is up and running.

2. : Displays custom application information, such as version, description, or any other relevant details.

3. : Exposes various metrics and statistics about the application, such as memory usage, HTTP request count, and response times.

4. : Allows access to the application's environment properties and configuration.

5. : Provides the ability to view and modify the application's logging configuration at runtime.

6. : Displays the most recent HTTP requests and their details, including request and response headers.

  • If you enable the Spring Boot Actuator in your application, you can easily access these endpoints and take advantage of the provided functionality.

  • The actuator endpoints can be exposed over HTTP or JMX (Java Management Extensions) and can be secured using Spring Security to restrict access to authorized users.

Why do we need an actuator spring boot?

  • Spring Boot Actuator is an essential tool for monitoring and managing Spring Boot applications in production environments. There are many important reasons why it is needed and beneficial for developers and operations teams. Let's discuss those reasons : 

1. Application Health Monitoring:

  • The actuator endpoints, such as , allow you to check the health status of your application.

  • It provides a quick way to determine if your application is up and running or if any issues need attention.

  • By monitoring the health endpoint, you can proactively identify and address any problems before they impact the users.

2. Metrics and Performance Monitoring:

  • The endpoint exposes various metrics and statistics about your application, such as memory usage, HTTP request count, and response times.

  • These metrics help you understand how your application is performing and identify potential bottlenecks or performance issues.

  • By collecting and analyzing these metrics, you can optimize your application's performance and ensure a better user experience.

3. Runtime Configuration Management:

  • The endpoint allows you to view and modify the application's environment properties and configuration at runtime.

  • This is particularly useful when you need to adjust configuration parameters without restarting the application.

  • It provides flexibility and ease of management in production environments.

4. Logging and Tracing:

  • The endpoint enables you to view and modify the application's logging configuration dynamically.

  • You can change the log levels of specific packages or classes without the need to restart the application.

  • Additionally, the endpoint captures the most recent HTTP requests and their details, which can be valuable for debugging and troubleshooting purposes.

5. Integration with Monitoring Tools:

  • Spring Boot Actuator integrates well with popular monitoring and management tools like Prometheus, Grafana, and ELK stack.

  • By exposing metrics and other data through the actuator endpoints, you can easily collect and visualize the information in these tools.

  • This integration enables centralized monitoring, alerting, and data analysis, making it easier to manage and maintain your applications.

6. Production Readiness:

  • The actuator endpoints provide a standardized way to expose application information and management capabilities.

  • By leveraging these endpoints, you can ensure that your application is production-ready and follows best practices for monitoring and management.

  • It helps in building robust and maintainable applications that can be easily operated and supported in production environments.

7. Debugging and Troubleshooting:

  • When issues arise in production, the actuator endpoints can be invaluable for debugging and troubleshooting.

  • By accessing endpoints like , , and , developers can gather detailed information about the application's state, recent requests, and thread dumps.

  • This information can help in identifying the root cause of problems and resolving them quickly.

Spring Boot Starter Actuator

  • Spring Boot Actuator provides secured endpoints for monitoring and managing the Spring Boot application.

  • By default, all actuator endpoints are secured. It provides several additional features that help us monitor and manage the Spring Boot application. It contains the actuator endpoints. 

  • With the help of actuator endpoints such as HTTP and JMX,  we can manage and monitor the spring boot applications.

  • To enable the production-ready features into your application, you can use Starter Actuator.

  • To enable Spring Boot Actuator into our Spring Boot application, we need to add spring-boot-starter-actuator dependency in the pom.xml file. 

You can see we have added this dependency into our pom.xml in the following picture:

Features of Spring Boot Actuator

There are three main features of the Actuator:

1.) Endpoints

2.) Metrics

3.) Audit

Let’s learn about these features.

Endpoints: 

  • The actuator endpoints will allow us to monitor and interact with the application. Spring Boot provides several built-in endpoints.

  • We can also create our own endpoint. Most of the applications choose HTTP, where the Id of the endpoint, along with the prefix of /actuator, is mapped to a URL.

For example, the /env endpoint is used to expose properties from Spring's ConfigurableEnvironment. By default, the actuator is mapped to it like this /actuator/env.

Metrics: 

  • Spring Boot Actuator provides metrics by integrating with the micrometer. The micrometer is integrated into Spring Boot.

  • A micrometer is a vendor-neutral metrics facade, meaning metrics can be collected in one way but revealed in the format required by many different monitoring systems.

Audit: 

  • Spring Boot provides an audit framework that produces events to an AuditEventRepository. It involuntarily publishes the authentication events if spring-security is in execution.

Spring Boot Actuator Endpoints

  • The actuator endpoints allow us to monitor and interact with the spring boot application. Spring Boot provides several built-in endpoints. We can also create our own endpoint.

Some of the most widely used endpoints are mentioned below:

1.) /metric: It is used to view the application metrics such as memory used, memory-free, threads, system uptime, etc.

2.) /env: It is used to view the list of Environment variables used in the application.

3.) /health: It is used to show the health of the application.

4.) /info: It is used to view the information about the Spring Boot application.

5.) /trace: It is used to view the list of Traces of your rest endpoints.

6.) /beans: It is used to show the complete list of all the Spring beans in your application.

 

Enabling Spring Boot Actuator

  • In this blog, we will fetch two endpoints to show how the endpoints work and have that idea; you can easily implement other endpoints.

Before you start fetching the endpoints make sure that you have injected the spring-boot-starter-actuator dependency into your pom.xml file.

Spring Boot actuator properties 

  • Spring Boot Actuator provides a wide range of configuration properties that allow you to customize and control the behavior of the actuator endpoints. These properties are defined in the or file of your Spring Boot application. 

Let's see some commonly used Spring Boot Actuator properties:

1. :

  • This property specifies which actuator endpoints should be exposed over HTTP. By default, only the endpoint is exposed.

  • You can set this property to to expose all endpoints or provide a comma-separated list of specific endpoints you want to expose.

2. :

  • This property sets the base path for the actuator endpoints. By default, it is set to .

  • For example, if you set this property to , the health endpoint would be accessible at .

3. :

  • This property allows you to enable or disable specific actuator endpoints.

  • For example, enables the health endpoint.

4. :

  • This property sets the cache time-to-live duration for the response of a specific endpoint. It is useful for endpoints that may have expensive computations.

  • For example, sets the cache TTL for the health endpoint to 10 seconds.

5. :

  • This property controls whether the default health indicators should be enabled.

  • By default, it is set to . You can set it to to disable the default health indicators.

6. :

  • This property allows you to enable or disable specific health indicators. For example, disables the database health indicator.

7. :

  • This property allows you to customize the information displayed by the endpoint. You can define arbitrary key-value pairs that will be included in the info response.

  • For example, sets the application name in the info response.

8. :

  • This property enables or disables specific metric exporters.

  • For example, enables the Prometheus metric exporter.

9. :

  • This property sets the port on which the management server (actuator endpoints) should listen. By default, it uses the same port as the application server.

  • You can set it to a different port to separate the management endpoints from the main application.

10. :

  • Similar to the web exposure property, this property specifies which actuator endpoints should be exposed over JMX. By default, all endpoints are exposed over JMX.

Spring Boot Actuator Example

Let's understand the concept of the actuator through an example.

Step 1: Open Spring Initializr https://start.spring.io/ and create a Maven project.

Step 2: Provide the Group name. We have provided com.javatpoint.

Step 3: Provide the Artifact Id. We have provided the spring-boot-actuator-example.

Step 4: Add the following dependencies: Spring Web, Spring Boot Starter Actuator, and Spring Data Rest HAL Browser.

Step 5: Click on the Generate button. When we click on the Generate button, it wraps all the specifications related to the project into a Jar file and downloads it to our local system.

Step 6: Extract the Jar file and paste it into the STS workspace.

Step 7: Import the project folder.

File -> Import -> Existing Maven Projects -> Browse -> Select the folder spring-boot-actuator-example -> Finish

It takes some time to import. After importing the project, we can see the project directory in the package explorer section.

Step 8: Create a Controller class. We have created the controller class with the name DemoRestController.

Step 9: Open the application.properties file and disable the security feature of the actuator by adding the following statement.

application.properties

management.security.enabled=false  

Step 10: Run the SpringBootActuatorExampleApplication.java file.

Step 11: Open the browser and invoke the URL http://localhost:8080/actuator. It returns the following page:

The application runs on port 8080 by default. Once the actuator has started, we can see the list of all the endpoints exposed over HTTP.

Let's invoke the health endpoint by invoking the URL http://localhost:8080/actuator/health. It denotes the status UP. It means the application is healthy and running without any interruption.

2️⃣ Spring Boot Starter Test

  • Spring Boot Starter Test is used for testing Spring Boot applications with libraries including JUnit Jupiter, Hamcrest, and Mockito. It is the primary dependency for the test. 

  • For testing, we need to add the spring-boot-starter-test dependency into the pom.xml file. 

When we create a spring boot application the spring-boot-starter-test is by default added into pom.xml.

  • It pulls all the dependencies related to test. After adding it, we can build up a simple unit test. We can either create the Spring Boot project through IDE or generate it using Spring Initializr.

  • In the above dependency, one thing to be noticed that it includes the scope of test <scope>test</scope>.

  • It means when the application is bundled and packaged for deployment, any dependency that is declared with the test scopes is ignored. The test scope dependencies are only available when running in the development and Maven test modes.

  • When we create a simple Spring Boot application, by default, it contains the test dependency in the pom.xml file and ApplicationNameTest.java file under in the folder src/test/java.

Let's create a simple maven project.

Spring Boot Starter Test Example

Step 1: Open Spring Initializr https://start.spring.io/.

Step 2: Provide the Group name and Artifact Id. We have provided Group name com.javatpoint and Artifact spring-boot-test-example.

Step 3: Add the Spring Web dependency.

Step 4: Click on the Generate button. When we click on the Generate button, it wraps all the specifications related to the project and downloads a Jar file to our local system.

Step 5: Extract the downloaded Jar file.

Step 6: Import the folder to STS. It takes some time to import.

File -> Import -> Existing Maven Projects -> Browse -> Select the folder spring-boot-test-example -> Finish

After importing the project, we can see the following project directory in the Package Explorer section of the STS.

We can see in the above directory that it contains a test file named SpringBootTestExampleApplicationTest.java in the folder src/test/java.

SpringBootTestExampleApplicationTest.java

The above code implements two annotation by default: @SpringBootTest, and @Test.

  • @SpringBootTest: It applies on a Test Class that runs Spring Boot based tests.

  • It provides the following features over and above the regular Spring TestContext Framework:It uses SpringBootContextLoader as the default ContextLoader if no specific @ContextConfiguration(loader=...) is defined.It automatically searches for a @SpringBootConfiguration when nested @Configuartion is not used, and no explicit classes are specified.It provides support for different WebEnvironment modes.

  • It registers a TestRestTemplate or WebTestClient bean for use in web tests that are using the webserver.It allows application arguments to be defined using the args attribute.

Step 7: Open the SpringBootTestExampleApplicationTest.java file and run it as Junit Test.

When we run the above code, it displays the following:

3️⃣ Spring Boot DevTools

  • Spring Boot DevTools is a collection of tools that help improve the application development experience with the Spring Boot framework.

  • It includes features like automatic restarts, live reloading, and enhanced debugging support.

  • The goal of Spring Boot DevTools is to make the development process more efficient so developers can focus on building applications instead of the development environment. 

Here are some of the features of Spring Boot DevTools: 

  • Automatic restart: Automatically restarts the application when files on the classpath change

  • LiveReload: Triggers a browser refresh when a resource is changed

  • Static resource caching: Caches static resources

  • Global settings: Provides global settings

  • Remote application running: Allows remote application running

  • To include Spring Boot DevTools in a project, add the module dependency to the build. Spring Boot DevTools also provides browser extensions for Chrome, Firefox, and Safari

We can implement the DevTools in our project by adding the following dependency in the pom.xml file.

Spring Boot DevTools Features

Spring Boot DevTools provides the following features:

  1. Property Defaults

  2. Automatic Restart

  3. LiveReload

  4. Remote Debug Tunneling

  5. Remote Update and Restart

Property Defaults:

  • Spring Boot provides templating technology Thymeleaf that contains the property spring.thymeleaf.cache.

  • It disables the caching and allows us to update pages without the need of restarting the application. But setting up these properties during the development always creates some problems.

  • When we use the spring-boot-devtools module, we are not required to set properties. During the development caching for Thymeleaf, Freemarker, Groovy Templates are automatically disabled.

Automatic Restart:

  • Auto-restart means reloading of Java classes and configure it at the server-side. After the server-side changes, it deployed dynamically, server restarts happen, and load the modified code. It is mostly used in microservice-based applications. Spring Boot uses two types of ClassLoaders:

  • The classes that do not change (third-Jars) are loaded in the base ClassLoader.

  • The classes that we are actively developing are loaded in the restart ClassLoader.

  • When the application restarts, the restart ClassLoader is thrown away, and a new one is populated. Therefore, the base ClassLoader is always available and populated.

  • We can disable the auto-restart of a server by using the property spring.devtools.restart.enabled to false.

LiveReload:

  • The Spring Boot DevTools module includes an embedded server called LiveReload.

  • It allows the application to automictically trigger a browser refresh whenever we make changes in the resources. It is also known as auto-refresh.

It provides browser extensions for Chrome, Firefox, and Safari. By default, LiveReload is enabled. The LiveReload works on the following path:

  • /META-INF/maven

  • /META-INF/resources

  • /resources

  • /static

  • /public

  • /templates

We can also disable auto-reload in browser by excluding the above paths. For example:

spring.devtools.restart.exclude=public/**, static/**, templates/**  

We can see the other additional path by using the property spring.devtools.restart.additional-paths. For example:

spring.devtools.restart.additional-paths=/path-to-folder  

If we want to exclude additional path and want to keep defaults then use the property spring.devtools.restart.additional-exclude. For example:

spring.devtools.restart.additional-exclude=styles/**  

Remote Debug Tunneling:

  • Spring Boot can tunnel JDWP (Java Debug Wire Protocol) over HTTP directly to the application.

  • It can even work application deployment to Internet Cloud providers that only expose port 80 and 443.

Remote Update and Restart:

  • There is another trick that DevTools offers is: it supports remote application updates and restarts.

  • It monitors local classpath for file changes and pushes them to a remote server, which is then restarted. We can also use this feature in combination with LiveReload.

Using a Trigger File

  • Automatic restart sometimes can slow down development time due to frequent restarts. To remove this problem, we can use a trigger file.

  • Spring Boot monitors trigger file and detects modifications in that file. It restarts the server and reloads all previous changes.

  • We can implement the trigger file in our application by adding the property spring.devtools.restart.trigger-file. The file can be internal or external. For example:

spring.devtools.restart.trigger-file=c:/workspace-sts-3.9.9.RELEASE/restart-trigger.txt  

Spring Boot DevTools Example

Step 1: Create a Maven project using Spring Initializr https://start.spring.io/.

Step 2: Provide the Group name and Artifact Id. We have provided Group name com.javatpoint and Artifact Id spring-boot-devtools-example.

Step 3: Add the following dependencies: spring-boot-starter-web and spring-boot-devtools.

Step 4: Click on the Generate button. It downloads the Jar file of the project.

Step 5: Extract the Jar file.

Step 6: Import the folder to STS. It takes time to import.

File -> Import -> Existing Maven Projects -> Browse -> Select the folder spring-boot-devtools-example -> Finish

When the project imports successfully, we can see the following directory in the Package Explorer section of the STS.

Step 7: Open the SpringBootDevtoolsExampleApplication.java and run it as Java Application.

After that, make any changes (edit or remove some file or code) in the application, and save that changes. As soon as we save the changes, the server restarts and pick up the changes.

Sridhar Raj P

🚀 On a mission to teach 1 million students | Developer & Mentor | 7,950+ Students 💜 | Material UI | JavaScript | React JS | Redux | React Native | Python | Java | Springboot | MySQL | Self-Learner | Problem Solver

7mo

Very informative

To view or add a comment, sign in

Others also viewed

Explore topics