How to add a custom health check in spring boot health?

Adding a custom health check is easy. Just create a new Java class, extend it from the AbstractHealthIndicator and implement the doHealthCheck method. The method gets a builder passed with some useful methods. Call builder.up() if your health is OK or builder.down() if it is not. What you do to check the health is completely up to you. Maybe you want to ping some server or check some files.

@Component
public class CustomHealthCheck extends AbstractHealthIndicator {
    @Override
    protected void doHealthCheck(Health.Builder bldr) throws Exception {
        // TODO implement some check
        boolean running = true;
        if (running) {
          bldr.up();
        } else {
          bldr.down();
        }
    }
}

This is enough to activate the new health check (make sure @ComponentScan is on your application). Restart your application and locate your browser to the /health endpoint and you will see the newly added health check.

{
    "status":"UP",
    "CustomHealthCheck": {
        "status":"UP"
    },
    "diskSpace": {
        "status":"UP",
        "free":56443746,
        "threshold":1345660
    }
}

Leave a Comment