← Java

Java · 24 / 24

Operate with health checks, metrics and CI

Verify a health endpoint and a counter for accepted jobs.

  • Large
  • Advanced
  • 90 min

Prerequisites: Spring Boot REST with validation, Spring Security: authentication and authorization

In this tutorial
  1. Read the domain contract
  2. Start an isolated environment
  3. Verify success and failure
  4. Make a regression visible
  5. Extend the contract
  6. Explain the solution and its limits
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

JDK 21, Maven 3.9 or newer. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.

Verified on 2026-10-20 on Linux x86_64. HTTP tests inspect health and the counter before and after an action. The CI file runs the same tests. A local health result does not prove operational alerting or recovery.

A running process does not prove a successful domain action. We separate technical health from a business counter. A valid request increments accepted.jobs while invalid input does not. The test reads the metric over HTTP. This local demo binds to loopback only and does not authorize public monitoring exposure.

Package contents and individual files

01Read the domain contract

Health describes availability and readiness. Metrics count observed operations. Logs explain individual events. These signals answer different questions and must not expose private data or create unbounded metric labels.

src/main/java/tutorial/Application.java · javaOpen file
package tutorial;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

@org.springframework.web.bind.annotation.RestController
class Jobs {

  private final io.micrometer.core.instrument.Counter accepted;
  private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(
    Jobs.class
  );

  Jobs(io.micrometer.core.instrument.MeterRegistry registry) {
    accepted = registry.counter("accepted.jobs");
  }

  @org.springframework.web.bind.annotation.PostMapping("/jobs")
  org.springframework.http.ResponseEntity<String> create(
    @org.springframework.web.bind.annotation.RequestBody String title
  ) {
    if (
      title.isBlank()
    ) return org.springframework.http.ResponseEntity.badRequest().body(
      "Title required"
    );
    accepted.increment();
    log.info("job accepted");
    return org.springframework.http.ResponseEntity.accepted().body("queued");
  }
}

02Start an isolated environment

Java 21 is the language baseline. Maven resolves dependencies from the POM. Tests use their own data. HTTP tests start a server on a randomly assigned local port.

pom.xml · xmlOpen file
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>4.1.0</version></parent>
<groupId>learning</groupId><artifactId>tutorial</artifactId><version>1.0</version>
<properties><java.version>21</java.version></properties>
<dependencies>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency>
</dependencies>
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

03Verify success and failure

HTTP tests inspect health and the counter before and after an action. The CI file runs the same tests. A local health result does not prove operational alerting or recovery.

src/test/java/tutorial/LessonTest.java · javaOpen file
package tutorial;

import static org.junit.jupiter.api.Assertions.*;

import java.net.*;
import java.net.http.*;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class LessonTest {

  @LocalServerPort
  int port;

  HttpResponse<String> get(String path) throws Exception {
    return HttpClient.newHttpClient().send(
      HttpRequest.newBuilder(
        URI.create("http://127.0.0.1:" + port + path)
      ).build(),
      HttpResponse.BodyHandlers.ofString()
    );
  }

  int post(String text) throws Exception {
    return HttpClient.newHttpClient()
      .send(
        HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + "/jobs"))
          .POST(HttpRequest.BodyPublishers.ofString(text))
          .header("Content-Type", "text/plain")
          .build(),
        HttpResponse.BodyHandlers.ofString()
      )
      .statusCode();
  }

  @Test
  void healthAndBusinessMetric() throws Exception {
    assertEquals(200, get("/actuator/health").statusCode());
    assertTrue(
      get("/actuator/metrics/accepted.jobs").body().contains("\"value\":0.0")
    );
    assertEquals(400, post(" "));
    assertTrue(
      get("/actuator/metrics/accepted.jobs").body().contains("\"value\":0.0")
    );
    assertEquals(202, post("Example"));
    assertTrue(
      get("/actuator/metrics/accepted.jobs").body().contains("\"value\":1.0")
    );
  }
}

Run / check

mvn test
Expected result

HTTP tests inspect health and the counter before and after an action. The CI file runs the same tests. A local health result does not prove operational alerting or recovery.

04Make a regression visible

Change a domain expectation and rerun the test. Maven must report failure. A skipped database test is not evidence. Restore the correct expectation afterwards.

05Extend the contract

Verify sensitive management endpoints are not accidentally exposed.

06Explain the solution and its limits

The solution expects 404 for /actuator/env. Only health and metrics are exposed. A production system additionally needs access control and defined log retention. Payload data is not logged here. Copy solution/LessonTest.java over the test file and repeat the same verification.

Expected result

All tests pass, including the additional solution expectation.

Your exercise

Verify sensitive management endpoints are not accidentally exposed.

Show the solution and explanation

The solution expects 404 for /actuator/env. Only health and metrics are exposed. A production system additionally needs access control and defined log retention. Payload data is not logged here.

solution/LessonTest.java · javaOpen file
package tutorial;

import static org.junit.jupiter.api.Assertions.*;

import java.net.*;
import java.net.http.*;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class LessonTest {

  @LocalServerPort
  int port;

  HttpResponse<String> get(String path) throws Exception {
    return HttpClient.newHttpClient().send(
      HttpRequest.newBuilder(
        URI.create("http://127.0.0.1:" + port + path)
      ).build(),
      HttpResponse.BodyHandlers.ofString()
    );
  }

  int post(String text) throws Exception {
    return HttpClient.newHttpClient()
      .send(
        HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + "/jobs"))
          .POST(HttpRequest.BodyPublishers.ofString(text))
          .header("Content-Type", "text/plain")
          .build(),
        HttpResponse.BodyHandlers.ofString()
      )
      .statusCode();
  }

  @Test
  void healthAndBusinessMetric() throws Exception {
    assertEquals(404, get("/actuator/env").statusCode());
    assertEquals(200, get("/actuator/health").statusCode());
    assertTrue(
      get("/actuator/metrics/accepted.jobs").body().contains("\"value\":0.0")
    );
    assertEquals(400, post(" "));
    assertTrue(
      get("/actuator/metrics/accepted.jobs").body().contains("\"value\":0.0")
    );
    assertEquals(202, post("Example"));
    assertTrue(
      get("/actuator/metrics/accepted.jobs").body().contains("\"value\":1.0")
    );
  }
}

Project context and sources

This independent learning project explores a topic in this technology area. Project references provide a pinned revision as architectural context. They do not imply that every library or feature introduced here is already used in that application.