Skip to content
javahacks.dev
Spring Boot

Spring Boot Guide From First Project to Production

Build, configure, test and package a Spring Boot 4 service, then see what separates a demo from a service you can run in production.

16 min read
Summarize in AI
Flat illustration of a start button surrounded by Spring Boot starters, with the Spring Boot, Docker and OpenJDK logos.

A Spring Boot application that runs on your laptop and one that survives a deploy are separated by a short list of settings, and nobody tells you the list until the first outage. This guide follows one small service from the Initializr page to a container image, on Spring Boot 4 and JDK 25, and stops at each setting that matters in production. If a step fails for you, the matching fix post is linked at the point where it usually does.

Spring Boot sits on the Spring container, so when a bean misbehaves, how the Spring container works is the page to read next.

Start from the Initializr

Create the project at start.spring.io with Maven, Java 25 and four dependencies: Spring Web, Validation, Actuator and Spring Data JPA with PostgreSQL. Resist adding more. Each starter brings auto-configuration, and the more of it you carry, the longer the list of reasons the application can fail to start.

The generated main class is the whole entry point:

src/main/java/dev/javahacks/shop/ShopApplication.javajava
@SpringBootApplication
public class ShopApplication {

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

@SpringBootApplication combines @Configuration, @EnableAutoConfiguration and @ComponentScan. The scan starts in the package of this class, which is why a controller placed in a sibling package is silently ignored and returns a whitelabel 404 page.

Keep configuration out of the code

Spring Boot reads application.properties or application.yaml from the classpath (externalized configuration), then overlays profile files, environment variables and command-line arguments, with the later sources winning. The environment variable SPRING_DATASOURCE_URL overrides spring.datasource.url because relaxed binding maps one to the other.

src/main/resources/application.yamlYAML
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/shop
    username: shop
  jpa:
    open-in-view: false
server:
  shutdown: graceful

The password is not in the file. In every environment but a laptop it arrives as SPRING_DATASOURCE_PASSWORD. The first time you forget to supply the datasource at all, you get the Failed to configure a DataSource report.

spring.jpa.open-in-view=false is a deliberate choice. The default keeps a database connection open for the entire web request, which hides lazy-loading mistakes in development and drains the pool under slow clients. Turning it off surfaces those mistakes early, and [LazyInitializationException](/library/lazyinitializationexception-fix-spring-boot-hibernate) is how they show up.

Validate properties at startup

Bind your own settings to a typed object so a typo cannot reach production:

src/main/java/dev/javahacks/shop/ShopProperties.javajava
@ConfigurationProperties(prefix = "shop")
@Validated
public record ShopProperties(
        @NotBlank String currency,
        @Min(1) @Max(100) int pageSize) {
}

Enable it with @ConfigurationPropertiesScan on the application class. If shop.page-size is missing or 0, the application refuses to start and names the property. That is the behavior you want: a failure on deploy, with the property in the message, instead of a surprise on the first request. A missing @Value placeholder fails the same way, and the placeholder error explains its message.

Write a controller and test it as a slice

src/main/java/dev/javahacks/shop/ProductController.javajava
@RestController
@RequestMapping("/api/products")
class ProductController {

    private final ProductRepository products;

    ProductController(ProductRepository products) {
        this.products = products;
    }

    @GetMapping("/{id}")
    ResponseEntity<Product> byId(@PathVariable long id) {
        return products.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
}

Constructor injection needs no annotation when the class has one constructor. Test the web layer without starting the database by loading only the MVC slice:

src/test/java/dev/javahacks/shop/ProductControllerTest.javajava
@WebMvcTest(ProductController.class)
class ProductControllerTest {

    @Autowired MockMvc mvc;
    @MockitoBean ProductRepository products;

    @Test
    void returns404ForUnknownProduct() throws Exception {
        given(products.findById(7L)).willReturn(Optional.empty());

        mvc.perform(get("/api/products/7"))
           .andExpect(status().isNotFound());
    }
}

@MockitoBean is the Spring Framework 6.2 replacement for the deprecated @MockBean. A full-context @SpringBootTest belongs to a handful of end-to-end checks; the slices keep the suite fast. If the context fails to load, Failed to load ApplicationContext lists the causes in order.

Add Actuator, and be careful what it exposes

Actuator turns on health, metrics and info endpoints (Actuator reference). Over HTTP, Spring Boot exposes only health by default, and you should keep it that way until you know who can reach the port.

YAML
management:
  endpoints:
    web:
      exposure:
        include: health, info
  endpoint:
    health:
      probes:
        enabled: true

With probes enabled, /actuator/health/liveness and /actuator/health/readiness exist for Kubernetes. Liveness answers whether the process should be restarted, so it must not depend on the database; readiness answers whether it should receive traffic, so it can. Mixing the two is how a database blip turns into a restart loop. Never expose env, heapdump or shutdown on a public port.

Shut down without dropping requests

With server.shutdown=graceful, Spring Boot stops accepting new connections on SIGTERM and waits for active requests, up to spring.lifecycle.timeout-per-shutdown-phase (30 seconds by default). Your orchestrator's termination grace period must be longer than that value, or the process is killed first.

Package a layered image

The Maven plugin builds an OCI image without a Dockerfile:

Shell
./mvnw -q spring-boot:build-image -Dspring-boot.build-image.imageName=shop:1.0

The image uses Cloud Native Buildpacks, which calculate memory settings from the container limit at startup. If you write your own Dockerfile instead, use the layered jar so dependencies and your code land in separate layers, and read the Docker image that will not start when the container exits immediately.

Read the failure analysis before anything else

Spring Boot prints a structured report when startup fails: a description, then an action. The two lines tell you most of what the stack trace will. The port conflict is the classic case, and port 8080 already in use shows how to find the process. For anything else, application failed to start is the checklist.

Persistence: an entity, a repository and a migration

The generated project has a datasource and no tables. Add the three pieces that make persistence reproducible. First, the entity. It is an ordinary class with a protected constructor for JPA, because a record cannot be proxied or mutated by Hibernate:

src/main/java/dev/javahacks/shop/Product.javajava
@Entity
@Table(name = "products")
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, length = 120)
    private String name;

    @Column(nullable = false, precision = 19, scale = 2)
    private BigDecimal price;

    @Version
    private long version;

    protected Product() {}

    public Product(String name, BigDecimal price) {
        this.name = name;
        this.price = price;
    }

    public Long getId() { return id; }
    public String getName() { return name; }
    public BigDecimal getPrice() { return price; }
}
src/main/java/dev/javahacks/shop/ProductRepository.javajava
public interface ProductRepository extends JpaRepository<Product, Long> {

    List<Product> findByNameContainingIgnoreCaseOrderByName(String fragment);
}

Second, the schema belongs in a migration, not in a Hibernate setting. Add the Flyway dependency (org.flywaydb:flyway-core and the PostgreSQL module for your Flyway version) and write the first version of the table:

src/main/resources/db/migration/V1__create_products.sqlSQL
create table products (
    id         bigint generated always as identity primary key,
    name       varchar(120)   not null,
    price      numeric(19, 2) not null check (price >= 0),
    version    bigint         not null default 0
);

create index products_name_idx on products (lower(name));

Third, tell Hibernate to verify and not to create:

YAML
spring:
  jpa:
    hibernate:
      ddl-auto: validate
  flyway:
    enabled: true

Now an application that starts has a schema that matches its mapping, and one that does not match refuses to start with a message that names the column. A migration that has already run in any shared environment is never edited, since Flyway stores a checksum and fails the next start if the file changed. A fix is a new version, V2__.... The mapping choices behind entities, such as lazy associations and fetch plans, are in the Hibernate guide.

Request objects, validation and one error format

Controllers should accept their own types, and never the entity. A record per request keeps the contract explicit and carries the validation rules:

java
public record CreateProduct(
        @NotBlank @Size(max = 120) String name,
        @NotNull @DecimalMin("0.00") @Digits(integer = 17, fraction = 2) BigDecimal price) {
}

public record ProductView(long id, String name, BigDecimal price) {
    static ProductView of(Product p) {
        return new ProductView(p.getId(), p.getName(), p.getPrice());
    }
}
java
@PostMapping
ResponseEntity<ProductView> create(@Valid @RequestBody CreateProduct request, UriComponentsBuilder uri) {
    Product saved = products.save(new Product(request.name(), request.price()));
    URI location = uri.path("/api/products/{id}").buildAndExpand(saved.getId()).toUri();
    return ResponseEntity.created(location).body(ProductView.of(saved));
}

A request that breaks a rule must come back as something a client can parse. Turn on the problem-details support and add one advice class for the errors that are yours:

YAML
spring:
  mvc:
    problemdetails:
      enabled: true
java
@RestControllerAdvice
class ApiExceptionHandler {

    @ExceptionHandler(ProductNotFound.class)
    ProblemDetail notFound(ProductNotFound e) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
        problem.setTitle("Product not found");
        return problem;
    }

    @ExceptionHandler(ObjectOptimisticLockingFailureException.class)
    ProblemDetail conflict() {
        return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT,
            "The product was changed by someone else. Reload and try again.");
    }
}

With that in place, a bad body yields 400 with application/problem+json that names the failing field, a missing product yields 404 in the same format, and a lost update yields 409. Every client then writes one error handler. The design rules behind these choices are the usual REST ones.

One configuration, three environments

Spring Boot loads application.yaml first and then any profile file that matches an active profile, so environment differences go in small overlay files. A layout that works for most teams:

src/main/resources/application-local.yamlYAML
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/shop
    username: shop
    password: shop
logging:
  level:
    org.hibernate.SQL: DEBUG
src/main/resources/application-prod.yamlYAML
spring:
  datasource:
    url: ${DB_URL}
    username: ${DB_USER}
    password: ${DB_PASSWORD}
  jpa:
    show-sql: false
management:
  endpoints:
    web:
      exposure:
        include: health, info, prometheus

Activate a profile with SPRING_PROFILES_ACTIVE=prod in the environment. Do not commit real credentials in the local file beyond a throwaway development password, and never put a production value in a file in the repository. On Kubernetes, mounted secrets can be read as configuration without environment variables at all:

YAML
spring:
  config:
    import: "optional:configtree:/etc/secrets/"

A file /etc/secrets/spring.datasource.password then becomes the property of the same name, which keeps the password out of docker inspect and process listings. Print the effective configuration of a running instance, with secrets masked, through the configprops and env Actuator endpoints in a protected profile, and not by guessing from the files.

Plain text lines are fine on a laptop and painful in a log platform. Spring Boot can write structured JSON through a property, with no extra dependency:

YAML
logging:
  structured:
    format:
      console: ecs

Each line becomes a JSON object with a timestamp, level, logger, message and any MDC fields, so a platform can filter by field instead of parsing text. Put a request id in the MDC in a filter, as in debugging production with logs, and every line of a request carries it. Choose levels on purpose: INFO for events a person operating the service wants to read, WARN for something recoverable that needs attention, ERROR only when someone should be paged, and DEBUG for development. Never log passwords, tokens, full card numbers or whole request bodies.

Metrics and a health check that tells the truth

Actuator publishes JVM, HTTP and connection pool metrics through Micrometer with no code. Add the metrics that describe your own business, because the platform cannot guess them:

java
@Service
class CheckoutService {

    private final Counter checkouts;
    private final Timer paymentTimer;

    CheckoutService(MeterRegistry registry) {
        this.checkouts = Counter.builder("shop.checkouts").tag("result", "completed").register(registry);
        this.paymentTimer = Timer.builder("shop.payment.duration").publishPercentileHistogram().register(registry);
    }

    void checkout(Cart cart) {
        paymentTimer.record(() -> payments.charge(cart));
        checkouts.increment();
    }
}

Add micrometer-registry-prometheus and expose prometheus in the management endpoints, and a scraper reads /actuator/prometheus. A custom health indicator reports a dependency that the default checks do not know about:

java
@Component
class PaymentGatewayHealth implements HealthIndicator {

    private final PaymentClient client;

    PaymentGatewayHealth(PaymentClient client) {
        this.client = client;
    }

    @Override
    public Health health() {
        try {
            client.ping();
            return Health.up().build();
        } catch (RuntimeException e) {
            return Health.down().withDetail("error", e.getClass().getSimpleName()).build();
        }
    }
}

Keep a dependency like this in the readiness group and out of liveness, as described earlier: if the gateway is down, the instance should stop receiving traffic that needs it, and a restart would not help.

YAML
management:
  endpoint:
    health:
      group:
        readiness:
          include: readinessState,db,paymentGateway

Secure the API from the first commit

A service without authentication is a demo. For an API that accepts bearer tokens from an identity provider, the configuration is short, and the default must be to deny:

java
@Configuration
@EnableMethodSecurity
class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        return http
            .csrf(csrf -> csrf.disable())
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/actuator/health/**").permitAll()
                .requestMatchers(HttpMethod.GET, "/api/products/**").hasAuthority("SCOPE_catalog:read")
                .requestMatchers("/api/**").hasAuthority("SCOPE_catalog:write")
                .anyRequest().denyAll())
            .oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()))
            .build();
    }
}
YAML
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://auth.example.com/realms/shop

CSRF protection is off here because the API holds no session cookie and authenticates with a header the browser does not attach on its own, which is the condition for turning it off safely. The final denyAll() means that a new endpoint nobody listed is closed until somebody decides who may call it. The explanations of each line are in the Spring Security lambda DSL post.

Outbound calls, pools and threads

Three settings decide how the service behaves when something it depends on is slow. Give every outbound HTTP call a timeout, because the default is often infinite:

java
@Bean
RestClient paymentsClient(RestClient.Builder builder) {
    var factory = new JdkClientHttpRequestFactory(
        HttpClient.newBuilder().connectTimeout(Duration.ofMillis(500)).build());
    factory.setReadTimeout(Duration.ofSeconds(2));
    return builder.baseUrl("https://payments.example.com").requestFactory(factory).build();
}

Size the database pool for the work and not for the thread count, with a short wait before a request gives up:

YAML
spring:
  datasource:
    hikari:
      maximum-pool-size: 10
      connection-timeout: 2000

Then decide on virtual threads. On a current JDK, one property gives each request a virtual thread, which suits services that spend their time waiting on I/O:

YAML
spring:
  threads:
    virtual:
      enabled: true

The pool becomes the throttle that protects the database, so keep the pool size where it was, and do not raise it to match the number of concurrent requests. The sizing arithmetic is in the HikariCP pool size post.

The integration test that proves the whole thing starts

Slice tests keep the suite fast, and one full test with a real database proves that the migrations, the mapping, the security and the controllers work together:

java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Testcontainers
class ShopApplicationIT {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17");

    @Autowired TestRestTemplate rest;

    @Test
    void healthIsUpAndAProductCanBeCreatedAndRead() {
        assertThat(rest.getForEntity("/actuator/health", String.class).getStatusCode())
            .isEqualTo(HttpStatus.OK);

        ResponseEntity<ProductView> created = rest.withBasicAuth("test", "test")
            .postForEntity("/api/products", new CreateProduct("Mug", new BigDecimal("12.50")), ProductView.class);

        assertThat(created.getStatusCode()).isEqualTo(HttpStatus.CREATED);
        assertThat(created.getHeaders().getLocation()).isNotNull();
    }
}

Test security with a test profile that supplies a fixed test token or a mock JWT decoder, and not with credentials copied from production. When the test fails at startup, read the report from the first section of this guide: a Flyway checksum mismatch, a validation error on a property and a missing bean all name themselves in the first lines.

A Dockerfile that uses the layers

The buildpack image is convenient. When you need a Dockerfile, use the layered jar so that the dependencies sit in their own layer and an ordinary code change rebuilds only a few kilobytes:

Dockerfile
FROM eclipse-temurin:25-jdk AS build
WORKDIR /workspace
COPY .mvn/ .mvn/
COPY mvnw pom.xml ./
RUN ./mvnw -q dependency:go-offline
COPY src/ src/
RUN ./mvnw -q -DskipTests package \
 && java -Djarmode=tools -jar target/shop.jar extract --layers --destination extracted

FROM eclipse-temurin:25-jre
WORKDIR /app
RUN useradd --system --uid 10001 app
COPY --from=build /workspace/extracted/dependencies/ ./
COPY --from=build /workspace/extracted/spring-boot-loader/ ./
COPY --from=build /workspace/extracted/snapshot-dependencies/ ./
COPY --from=build /workspace/extracted/application/ ./
USER app
EXPOSE 8080
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=65", "-jar", "shop.jar"]

Each line of this file has a reason, explained in writing a Dockerfile for Java the right way. Check the Spring Boot container images chapter for the exact extract command your version supports.

The deployment that matches the settings

The application settings only work if the platform cooperates. A Kubernetes deployment that agrees with everything above:

YAML
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop
spec:
  replicas: 3
  selector:
    matchLabels: { app: shop }
  template:
    metadata:
      labels: { app: shop }
    spec:
      terminationGracePeriodSeconds: 45
      containers:
        - name: shop
          image: registry.example.com/shop:1.0
          ports:
            - containerPort: 8080
          envFrom:
            - secretRef: { name: shop-db }
          env:
            - name: SPRING_PROFILES_ACTIVE
              value: prod
          resources:
            requests: { cpu: "500m", memory: "768Mi" }
            limits: { memory: "768Mi" }
          startupProbe:
            httpGet: { path: /actuator/health/liveness, port: 8080 }
            failureThreshold: 30
            periodSeconds: 2
          livenessProbe:
            httpGet: { path: /actuator/health/liveness, port: 8080 }
          readinessProbe:
            httpGet: { path: /actuator/health/readiness, port: 8080 }

The grace period of 45 seconds exceeds the 30-second shutdown phase, so Kubernetes does not kill a pod that is still draining. The memory limit is set equal to the request, and the JVM sizes its heap as a share of it. The startup probe gives a slow start up to a minute before liveness begins to judge it, so a cold JVM is not killed in a restart loop. If a pod is still killed, see the post on Java container OOMKilled errors.

A checklist before the first production deploy

QuestionWhere it is answered
Does the application start with only environment variables and a profile?application-prod.yaml and a staging run
Are all secrets outside the repository and the image?Secret store, configtree
Does a missing required property stop the startup with a clear message?@ConfigurationProperties with @Validated
Is the schema owned by migrations and verified at startup?Flyway and ddl-auto: validate
Is every outbound call bounded by a timeout?Client factories
Are liveness and readiness separate, and does liveness avoid dependencies?Health groups
Do SIGTERM and the grace period let in-flight requests finish?server.shutdown, pod settings
Can you find one request in the logs by an id?Structured logging and a filter
Do you know the three numbers that mean healthy, such as error rate, p99 latency and pool wait?Dashboards from Micrometer
Can you roll back, and have you tried it?The deployment pipeline

If the answer to any row is unknown, the work for the week is clear. Most outages in a first production service are on this list, and the list is short enough to finish before the launch.

Reading the startup failures you will meet

A startup that fails prints a report with a description and an action. Learn the common ones by sight:

First line of the descriptionUsual causeFirst move
Failed to configure a DataSource: 'url' attribute is not specifiedNo datasource properties in this profileSet the URL, or check which profile is active
Web server failed to start. Port 8080 was already in useAnother process holds the portFind it with lsof -i :8080 or change the port
Parameter 0 of constructor in ... required a bean of type ... that could not be foundMissing bean, or a package outside the scanCheck the package of the main class
Validation failed for ... shop.page-sizeA required property is missing or out of rangeSet it for this environment
Migration checksum mismatch for migration version 1A shipped migration was editedRestore the file, add a new version
Schema-validation: missing column [...] in table [...]The mapping and the migrations disagreeAdd the migration, or fix the field

Read the description before the stack trace, because it is written to be read by the person deploying, and the trace is written for the person fixing the framework. When the description is not enough, start the application with --debug and read the condition evaluation report, as described in the Spring Boot debugging post.

What to do in the second week

A service that passes the checklist is ready for its first users, and it is not finished. The second week is for the things that only real traffic teaches. Watch the dashboards you built and write down the three numbers that mean healthy: the error rate, the high percentile of latency, and how long requests wait for a database connection. Set an alert on each, with a threshold you can defend, and a link to the runbook in the alert text. Run the rollback once, on purpose, during working hours, so that the first rollback is not also the first time anyone has tried it.

Then read the logs from the first days with fresh eyes. Warnings that repeat are either noise to remove or a problem to fix, and an application whose logs are quiet when healthy is one where a new line stands out. Finally, schedule the dull maintenance now: a dependency update every month, a review of the pool and timeout settings after the first traffic peak and a restore test of the database backup. None of it is glamorous, and it is what separates a service that was launched from one that is operated.

When this setup is the wrong fit

This guide assumes a conventional servlet application on a JVM. If startup time and memory dominate the bill, as in scale-to-zero functions, look at Quarkus for Spring developers before you add native-image complexity to Spring. If the service is a thin transformation with no database, the Actuator and layered image advice still holds, but the persistence settings do not.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.