spring-boot-info-actuator-custom
Custom Information in Spring Boot Info Endpoint
1. Overview
In this quick article, we’ll have a look at how to customize the Spring Boot Actuators’ /info endpoint.
Please refer to this article to learn more about actuators in Boot and how to configure them.
2. Static Properties in /info
If we have some static information like the name of the application or it’s version that does not change for a long time, then it’s a good idea to add that details in our application.properties file:
## Configuring info endpoint
info.app.name=Spring Sample Application
info.app.description=This is my first spring boot application
info.app.version=1.0.0
That’s all we need to do to make this data available on the /info endpoint. Spring will automatically add all the properties prefixed with info to the /info endpoint:
{
"app": {
"description": "This is my first spring boot application",
"version": "1.0.0",
"name": "Spring Sample Application"
}
}
3. Environment Variables in /info
info.java-vendor = ${java.specification.vendor}
This will expose the Java vendor to our /info endpoint:
{
"app": {
"description": "This is my first spring boot application",
"version": "1.0.0",
"name": "Spring Sample Application"
},
"java-vendor": "Oracle Corporation",
}
Please note that all the environment variables are already available on the /env endpoint. However, the same can be exposed quickly on the /info endpoint as well.
4. Custom Data From the Persistence Layer
To achieve this, we need to implement InfoContributor interface and override the contribute() method:
@Component
public class TotalUsersInfoContributor implements InfoContributor {
@Autowired
UserRepository userRepository;
@Override
public void contribute(Info.Builder builder) {
Map<String, Integer> userDetails = new HashMap<>();
userDetails.put("active", userRepository.countByStatus(1));
userDetails.put("inactive", userRepository.countByStatus(0));
builder.withDetail("users", userDetails);
}
}
The first thing is that we need to mark the implementing class as a @Component. Then add the required details to the Info.Builder instance provided to the contribute() method.
This approach provides us a lot of flexibility regarding what we can expose to our /info endpoint:
{
...other /info data...,
...
"users": {
"inactive": 2,
"active": 3
}
}
5. Conclusion
Note that we’re also discussing how to add git information into the /info endpoint.
As always, the complete source code of this article can be found over on GitHub.