How to get Spring Actuator Health Status through Java Code?

Jasvinder S Saggu
2 min readSep 28, 2021

Spring Actuator exposes a web API to get the overall health of a SpringBoot application. This web endpoint is typically consumed by monitoring applications to monitor the health of a Spring application.

Occasionaly you also like to read the health of your application within Java code so you can perform certain actions. For example send notifications or stop consuming requests. This could be very useful when you application is reading data from some middleware. So instead of reading and then failing, you can proactively stop consuming the messages until your applciation becomes healthier again.

So How Do I consume the Actuator response within my applciation too?

Typically I have seen developers invoking the health web endpoint and parse the output. Which is okay but requires a lot of boiler plate code and it’s error prone.

Better way to consume actuator response is by using the beans which are exposing the status itself. Based on your needs you can either get the aggregated health status: UP or DOWN (1). Or you can go one step further and investigate which HealthIndicator component is actually down (2).

I hope you know that in order to provide health every Bean has to implment HealthIndicator interface.

  1. Aggregated Health Status
import org.springframework.stereotype.Component;
import org.springframework.boot.actuate.health.Status;
@Component
public class MyHealthStatusProvider {
private final HealthEndpoint healthEndpoint; public MyHealthStatusProvider(HealthEndpoint healthEndpoint) {
this.healthEndpoint = healthEndpoint;
}
public Status getHealthStatus() {
return this.healthEndpoint.health().getStatus();
}
}

2. Fine grained Component Level Heal Status

import org.springframework.boot.actuate.health.HealthIndicator;@Component
public class MyComponentHealthStatusProvider {
private final List<HealthIndicator> healthIndicators; public MyHealthStatusProvider(List<HealthIndicator> healthIndicators) {
this.healthIndicators = healthIndicators;
}
public List<HealthIndicator> getHealthStatus() {
return this.healthIndicators;
}
}

That’s it. Now you can very easily call these methods and get the applciation health status.

--

--