Spring Boot
Build a small Inventory API with Spring Boot 3.5, package it on a Red Hat UBI image, and run it on OpenShift with probes, a ConfigMap and a Secret.
ShopLite splits orders, catalog and notifications across three .NET services. This lab is the Java sibling, and it is one service on purpose: an Inventory API that lists warehouse stock and adjusts it. The platform pieces are the same ones ShopLite needed from OpenShift: a UBI image, a Deployment, a Service, a Route, probes, a ConfigMap and a Secret.
It was written for Spring Boot 3.5 on Java 21 and OpenShift 4.22. Stock lives in memory: fine for a deployment lab, and the wrong place for a real warehouse count.
GET /items lists every SKU, the on-hand quantity, and whether it is at or under the low-stock line. POST /items/{sku}/adjust with {"delta": -1} changes that quantity. A ConfigMap holds the warehouse code and the threshold. A Secret holds the API key callers send as X-Api-Key. Actuator serves /actuator/health/liveness and /actuator/health/readiness for the probes. Calls without the key get HTTP 401. The probe paths do not check the key.
Prerequisites
- JDK 21 and Maven (
java -version,mvn -version) - Podman or Docker
- An OpenShift 4.x cluster and
oc. The cluster can pullregistry.access.redhat.com/ubi9/openjdk-21andubi9/openjdk-21-runtime
Step 1: Create the project
mkdir inventory && cd inventory
pom.xml:
<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>3.5.5</version>
</parent>
<groupId>com.comptech</groupId>
<artifactId>inventory</artifactId>
<version>1.0.0</version>
<properties><java.version>21</java.version></properties>
<dependencies>
<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>
src/main/resources/application.properties:
server.port=8080
app.warehouse=${APP_WAREHOUSE:lab}
app.low-stock=${APP_LOW_STOCK:5}
app.api-key=${APP_API_KEY:dev-key}
management.endpoint.health.probes.enabled=true
management.health.livenessstate.enabled=true
management.health.readinessstate.enabled=true
management.endpoints.web.exposure.include=health
The placeholders are the contract. OpenShift fills APP_WAREHOUSE, APP_LOW_STOCK and APP_API_KEY. Locally the defaults after the colon are enough. Dotted keys belong in this properties file; the same dots as YAML keys would be one literal name, not a nested property.
Step 2: The API
src/main/java/com/comptech/inventory/InventoryApplication.java:
package com.comptech.inventory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
@SpringBootApplication
public class InventoryApplication {
public static void main(String[] args) {
SpringApplication.run(InventoryApplication.class, args);
}
}
record Item(String sku, String name, int onHand, boolean lowStock) {}
record Adjust(int delta) {}
@RestController
class InventoryController {
private final int lowStock;
private final String apiKey;
private final Map<String, int[]> stock = new ConcurrentHashMap<>();
InventoryController(@Value("${app.low-stock}") int lowStock,
@Value("${app.api-key}") String apiKey) {
this.lowStock = lowStock;
this.apiKey = apiKey;
stock.put("SRV-RACK", new int[] {12});
stock.put("GPU-NODE", new int[] {2});
stock.put("TOR-SW", new int[] {7});
}
@GetMapping("/items")
java.util.List<Item> items(@RequestHeader("X-Api-Key") String key) {
auth(key);
return stock.entrySet().stream()
.map(e -> toItem(e.getKey(), e.getValue()[0])).toList();
}
@PostMapping("/items/{sku}/adjust")
Item adjust(@RequestHeader("X-Api-Key") String key,
@PathVariable String sku, @RequestBody Adjust body) {
auth(key);
int[] onHand = stock.get(sku);
if (onHand == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND);
int next = onHand[0] + body.delta();
if (next < 0) throw new ResponseStatusException(HttpStatus.CONFLICT, "below zero");
onHand[0] = next;
return toItem(sku, next);
}
private void auth(String key) {
if (!apiKey.equals(key)) throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
}
private Item toItem(String sku, int onHand) {
return new Item(sku, sku, onHand, onHand <= lowStock);
}
}
The int array is a one-element holder so the quantity can change in place. The name in the JSON is the SKU.
Step 3: Run it locally
mvn -q spring-boot:run
curl -s localhost:8080/items -H 'X-Api-Key: dev-key'
curl -s -X POST localhost:8080/items/GPU-NODE/adjust \
-H 'X-Api-Key: dev-key' -H 'Content-Type: application/json' -d '{"delta": -1}'
curl -s -o /dev/null -w '%{http_code}\n' localhost:8080/items
curl -s localhost:8080/actuator/health/liveness
curl -s localhost:8080/actuator/health/readiness
The third call has no key and prints 401. Both health calls return {"status":"UP"} with no header. Liveness is only the process. A later database check belongs on readiness, or a database blip restarts every pod. The .NET lab makes the same split.
Step 4: Image on UBI
The builder compiles. The runtime image is what OpenShift runs. It already listens on 8080 as user 185.
Dockerfile:
FROM registry.access.redhat.com/ubi9/openjdk-21 AS build
WORKDIR /build
COPY --chown=185:0 pom.xml .
COPY --chown=185:0 src src
USER 185
RUN mvn -B -DskipTests package
FROM registry.access.redhat.com/ubi9/openjdk-21-runtime
COPY --from=build --chown=185:0 /build/target/inventory-1.0.0.jar /deployments/app.jar
EXPOSE 8080
ENV JAVA_APP_JAR=app.jar
podman build -t inventory:1 .
podman run --rm -p 8080:8080 -e APP_API_KEY=dev-key inventory:1
A .dockerignore containing target/ keeps the local build out of the context. run-java.sh launches the jar in /deployments.
Step 5: Deploy
oc new-project inventory
oc new-build --binary --strategy=docker --name=inventory
oc start-build inventory --from-dir=. --follow
oc create configmap inventory-config --from-literal=warehouse=dhk-1 --from-literal=low-stock=5
oc create secret generic inventory-secret --from-literal=api-key=change-me
deploy/inventory.yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
name: inventory
spec:
replicas: 2
selector:
matchLabels: { app: inventory }
template:
metadata:
labels: { app: inventory }
spec:
containers:
- name: inventory
image: image-registry.openshift-image-registry.svc:5000/inventory/inventory:latest
ports: [{ containerPort: 8080 }]
env:
- { name: APP_WAREHOUSE, valueFrom: { configMapKeyRef: { name: inventory-config, key: warehouse } } }
- { name: APP_LOW_STOCK, valueFrom: { configMapKeyRef: { name: inventory-config, key: low-stock } } }
- { name: APP_API_KEY, valueFrom: { secretKeyRef: { name: inventory-secret, key: api-key } } }
readinessProbe: { httpGet: { path: /actuator/health/readiness, port: 8080 }, periodSeconds: 10 }
livenessProbe: { httpGet: { path: /actuator/health/liveness, port: 8080 }, periodSeconds: 10 }
startupProbe: { httpGet: { path: /actuator/health/liveness, port: 8080 }, failureThreshold: 30, periodSeconds: 2 }
resources:
requests: { cpu: 100m, memory: 256Mi }
limits: { memory: 512Mi }
---
apiVersion: v1
kind: Service
metadata: { name: inventory }
spec:
selector: { app: inventory }
ports: [{ port: 80, targetPort: 8080 }]
---
apiVersion: route.openshift.io/v1
kind: Route
metadata: { name: inventory }
spec:
to: { kind: Service, name: inventory }
tls: { termination: edge, insecureEdgeTerminationPolicy: Redirect }
The startup probe gives the JVM time to open before liveness can restart it. Readiness pulls a pod out of the Service. There is no CPU limit: a limit here mostly throttles the garbage collector, and run-java.sh already sizes the heap from the memory limit. APP_WAREHOUSE is in the pod (oc exec deploy/inventory -- printenv APP_WAREHOUSE) and is not in the JSON yet. Two replicas do not share the in-memory map: an adjust on one pod can be missing from the next GET. Scale to 1 while you curl, or accept that a real count belongs in one database.
oc apply -f deploy/inventory.yaml
oc rollout status deployment/inventory
KEY=$(oc get secret inventory-secret -o jsonpath='{.data.api-key}' | base64 -d)
curl -sk "https://$(oc get route inventory -o jsonpath='{.spec.host}')/items" \
-H "X-Api-Key: $KEY"
Spring Boot reads the threshold at startup, so a ConfigMap edit does nothing until the pod is new: oc set data configmap/inventory-config low-stock=3 and oc rollout restart deployment/inventory. Delete a pod with oc delete pod -l app=inventory --wait=false and watch a new one take its place.
Troubleshooting
mvn missing in the build means the builder was the runtime image: compile on ubi9/openjdk-21, run on openjdk-21-runtime. Restarts during startup usually mean liveness is pointed at /items or at a path that checks the API key. HTTP 401 with health UP means the Secret does not match the header. The local default dev-key is not on the cluster. ErrImagePull means the project is not inventory or the build has not finished (oc get builds).
What's next
Quarkus is the same kind of service with health and metrics, on the JVM or as a native binary. ShopLite on .NET is the three-service version, with Postgres and Kafka. OpenTelemetry is how traces leave the pod. In production the map becomes a database, the key becomes a token from WSO2 Identity Server, and the Route sits behind WSO2 API Manager.