Java NotesRohit’s interview study guide
Chapter 16

Security and Production

What it takes to run a Spring Boot service for real: Spring Security's filter chain, securing an API with HTTP Basic and JWT bearer tokens, password storage, CORS and CSRF, Actuator health and metrics, logging, observability, and packaging the app into a container image. Every example was run with Spring Boot 4.2.0 (Spring Security 7.2) on Java 25.

Try it yourself. Same setup as chapter 13: the starter project plus the files shown, the app running with ./mvnw spring-boot:run, and curl in a second terminal. Where an example needs another starter, it says "add this to pom.xml": paste the <dependency> inside the starter's <dependencies>. Runner-style examples (they print and exit) use chapter 12's four-line application.properties and ./mvnw -q spring-boot:run.

9 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#Spring Security: the filter chain

Added

Spring Security is a chain of servlet filters that every request passes through before it reaches your controllers (filters, chapter 13). Each filter does one job: read credentials from a header, check a session, check a CSRF token, decide whether the authenticated user may call this URL. If a filter says no, the request never reaches your code: the chain answers 401 Unauthorized (who are you?) or 403 Forbidden (you can't do that).

In Express terms, it's a stack of app.use() middleware for auth, mounted before the router, plus a SecurityContext that holds "who is calling" for the rest of the request (like req.user set by Passport). Two classes you'll hear about: Tomcat calls one filter, DelegatingFilterProxy, which hands over to Spring's FilterChainProxy, which runs the filters of the matching SecurityFilterChain bean. You configure security by defining that bean.

The most surprising part for newcomers: adding the starter secures everything at once. Boot's defaults lock every endpoint, create one user called user with a random password printed in the log, and enable HTTP Basic and a login form.

Add this to pom.xml:

pom.xml
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
src/main/java/com/example/shop/HelloController.java
package com.example.shop;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
class HelloController {
    @GetMapping("/hello")
    String hello() {
        return "Hello";
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.security.user.password=change-me
Terminal
$ curl -si localhost:8080/hello | head -1
HTTP/1.1 401
$ curl -si localhost:8080/hello | grep WWW-Authenticate
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
$ curl -s -u user:wrong -o /dev/null -w "%{http_code}\n" localhost:8080/hello
401
$ curl -s -u user:change-me localhost:8080/hello
Hello
$ curl -s -o /dev/null -w "%{http_code}\n" localhost:8080/actuator/health
200
What’s happening
  1. The only change is the security starter (plus a fixed password for the default user, so the example is repeatable; without it Boot generates one and logs it as Using generated security password: …).
  2. /hello without credentials: 401. The response carries WWW-Authenticate: Basic realm="Realm", charset="UTF-8", which tells clients (and browsers) to send HTTP Basic credentials.
  3. Wrong password: still 401. With -u user:change-me, curl sends Authorization: Basic dXNlcjpjaGFuZ2UtbWU= (the Base64 of user:change-me) and the request reaches the controller: Hello.
  4. The one exception is Actuator's health endpoint: 200 without credentials. Boot's default security leaves health open so load balancers and Kubernetes probes keep working; everything else, including the other Actuator endpoints, needs a login. Secure by default means you open things up deliberately, which is the right way round.
  5. These defaults are for getting started. Real apps define their own SecurityFilterChain (next topic), and Boot's defaults step aside.

#Securing an API

Added

For an API you write a SecurityFilterChain bean that says, per URL pattern, who may call it, and which ways of logging in are accepted. The rules are checked top to bottom, first match wins, so specific rules go first and anyRequest() goes last. Roles are checked with hasRole("ADMIN"); a role is just an authority named ROLE_ADMIN.

Two styles of authentication matter for APIs:

  • HTTP Basic: username and password on every request. Simple, fine for internal tools and service-to-service calls over HTTPS, and the easiest to start with.
  • Bearer tokens (JWT): the client gets a signed token once (from an identity provider), then sends Authorization: Bearer <token>. The API checks the signature and reads the user and permissions from the token, with no database lookup and no session. This is what Spring calls an OAuth2 resource server, and it's how most production APIs behind a web or mobile app are secured.

HTTP Basic with roles

Add this to pom.xml:

pom.xml
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
src/main/java/com/example/shop/SecurityConfig.java
package com.example.shop;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableMethodSecurity
class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(HttpMethod.GET, "/products/**").permitAll()
                        .requestMatchers("/actuator/health").permitAll()
                        .requestMatchers(HttpMethod.DELETE, "/products/**").hasRole("ADMIN")
                        .anyRequest().authenticated())
                .httpBasic(Customizer.withDefaults())
                .csrf(csrf -> csrf.disable())
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        return http.build();
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    UserDetailsService users(PasswordEncoder encoder) {
        return new InMemoryUserDetailsManager(
                User.withUsername("rohit").password(encoder.encode("rohit-pass")).roles("USER").build(),
                User.withUsername("ana").password(encoder.encode("ana-pass")).roles("USER", "ADMIN").build());
    }
}
src/main/java/com/example/shop/ProductController.java
package com.example.shop;

import java.security.Principal;

import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
class ProductController {

    @GetMapping("/products/{id}")
    String one(@PathVariable long id) {
        return "product " + id;
    }

    @PostMapping("/products")
    String create(Principal user) {
        return "created by " + user.getName();
    }

    @DeleteMapping("/products/{id}")
    ResponseEntity<Void> delete(@PathVariable long id) {
        return ResponseEntity.noContent().build();
    }

    @GetMapping("/reports/sales")
    @PreAuthorize("hasRole('ADMIN')")
    String sales() {
        return "sales report";
    }
}
Terminal
$ curl -s localhost:8080/products/1
product 1
$ curl -s -o /dev/null -w "%{http_code}\n" -X POST localhost:8080/products
401
$ curl -s -u rohit:rohit-pass -X POST localhost:8080/products
created by rohit
$ curl -s -u rohit:rohit-pass -o /dev/null -w "%{http_code}\n" -X DELETE localhost:8080/products/1
403
$ curl -s -u ana:ana-pass -o /dev/null -w "%{http_code}\n" -X DELETE localhost:8080/products/1
204
$ curl -s -u rohit:rohit-pass -o /dev/null -w "%{http_code}\n" localhost:8080/reports/sales
403
$ curl -s -u ana:ana-pass localhost:8080/reports/sales
sales report
What’s happening
  1. authorizeHttpRequests lists the URL rules in order: anyone may GET products and the health check, only ADMIN may DELETE products, and everything else needs a logged-in user. httpBasic accepts Basic credentials. Defining this bean replaces Boot's default chain.
  2. csrf.disable() and a STATELESS session policy are right for an API that clients call with credentials on every request and no browser cookies (CORS and CSRF explains why). The users live in memory with hashed passwords (next topic).
  3. GET /products/1 needs no login: product 1. POST without credentials: 401. With Rohit's: the controller gets the logged-in user as a Principal: created by rohit.
  4. Rohit is only USER, so his DELETE is 403: authenticated, but not allowed. Ana has ADMIN: 204.
  5. /reports/sales falls under anyRequest().authenticated(), so Rohit gets past the URL rules, but method security stops him: @PreAuthorize("hasRole('ADMIN')") (enabled by @EnableMethodSecurity) checks again when the method is called, through a proxy (chapter 12). Rohit gets 403, Ana gets sales report.
AdvancedJWT bearer tokens: an OAuth2 resource server

In production, tokens come from an identity provider (Keycloak, Auth0, Okta, Amazon Cognito, Entra ID): the user signs in there, the client receives a signed JWT, and your API only verifies tokens. You'd point Spring at the provider with one property, spring.security.oauth2.resourceserver.jwt.issuer-uri, and Spring fetches its public keys and checks each token's signature, expiry and issuer.

To keep this runnable without an identity provider, the app below also issues tokens itself, signed with a shared secret (HS256) at a /token endpoint that takes Basic credentials. The verifying side is exactly what you'd use with a real provider.

Add this to pom.xml:

pom.xml
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security-oauth2-resource-server</artifactId>
		</dependency>
src/main/java/com/example/shop/JwtConfig.java
package com.example.shop;

import java.nio.charset.StandardCharsets;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.nimbusds.jose.jwk.source.ImmutableSecret;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
class JwtConfig {

    private final SecretKey key;

    JwtConfig(@Value("${shop.jwt-secret}") String secret) {
        this.key = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
    }

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/admin/**").hasAuthority("SCOPE_admin")
                        .anyRequest().authenticated())
                .httpBasic(Customizer.withDefaults())
                .oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()))
                .csrf(csrf -> csrf.disable())
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        return http.build();
    }

    @Bean
    JwtDecoder jwtDecoder() {
        return NimbusJwtDecoder.withSecretKey(key).macAlgorithm(MacAlgorithm.HS256).build();
    }

    @Bean
    JwtEncoder jwtEncoder() {
        return new NimbusJwtEncoder(new ImmutableSecret<>(key));
    }

    @Bean
    UserDetailsService users() {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        return new InMemoryUserDetailsManager(
                User.withUsername("rohit").password(encoder.encode("rohit-pass")).roles("USER").build());
    }
}
src/main/java/com/example/shop/TokenController.java
package com.example.shop;

import java.time.Instant;
import java.util.List;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
class TokenController {

    private final JwtEncoder encoder;

    TokenController(JwtEncoder encoder) {
        this.encoder = encoder;
    }

    // Stands in for an identity provider: trades Basic credentials for a signed, short-lived token.
    @PostMapping("/token")
    String token(Authentication login) {
        Instant now = Instant.now();
        JwtClaimsSet claims = JwtClaimsSet.builder()
                .issuer("shop")
                .subject(login.getName())
                .issuedAt(now)
                .expiresAt(now.plusSeconds(900))
                .claim("scope", "orders:read")
                .build();
        JwsHeader header = JwsHeader.with(MacAlgorithm.HS256).build();
        return encoder.encode(JwtEncoderParameters.from(header, claims)).getTokenValue();
    }

    record Me(String user, String issuer, List<String> authorities) {
    }

    @GetMapping("/me")
    Me me(@AuthenticationPrincipal Jwt jwt, Authentication auth) {
        List<String> authorities = auth.getAuthorities().stream().map(GrantedAuthority::getAuthority).sorted().toList();
        return new Me(jwt.getSubject(), jwt.getClaimAsString("iss"), authorities);
    }

    @GetMapping("/admin/stats")
    String stats() {
        return "admin only";
    }
}
src/main/resources/application.properties
spring.application.name=shop
shop.jwt-secret=a-demo-secret-that-is-at-least-32-bytes-long
Terminal
$ curl -s -o /dev/null -w "%{http_code}\n" localhost:8080/me
401
$ curl -s -u rohit:rohit-pass -X POST localhost:8080/token | cut -d. -f1
eyJhbGciOiJIUzI1NiJ9
$ TOKEN=$(curl -s -u rohit:rohit-pass -X POST localhost:8080/token) && curl -s localhost:8080/me -H "Authorization: Bearer $TOKEN"
{"user":"rohit","issuer":"shop","authorities":["FACTOR_BEARER","SCOPE_orders:read"]}
$ TOKEN=$(curl -s -u rohit:rohit-pass -X POST localhost:8080/token) && curl -s -o /dev/null -w "%{http_code}\n" localhost:8080/admin/stats -H "Authorization: Bearer $TOKEN"
403
$ TOKEN=$(curl -s -u rohit:rohit-pass -X POST localhost:8080/token) && curl -si localhost:8080/me -H "Authorization: Bearer ${TOKEN}x" | grep -E "^(HTTP|WWW)"
HTTP/1.1 401 
WWW-Authenticate: Bearer error="invalid_token", error_description="An error occurred while attempting to decode the Jwt: Signed JWT rejected: Invalid signature", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1", resource_metadata="http://localhost:8080/.well-known/oauth-protected-resource"
What’s happening
  1. The filter chain accepts two kinds of credentials: Basic (for /token) and bearer JWTs (oauth2ResourceServer(… jwt …)), verified by the JwtDecoder bean with the shared HS256 key. /admin/** needs the authority SCOPE_admin.
  2. /me with no credentials: 401. POST /token with Basic credentials returns a JWT: three Base64URL parts joined by dots. The first part is the header, eyJhbGciOiJIUzI1NiJ9, which decodes to {"alg":"HS256"}; the second holds the claims; the third is the signature.
  3. Sending the token as Authorization: Bearer … reaches /me. Spring verified the signature and expiry, then turned the scope claim into authorities with a SCOPE_ prefix: SCOPE_orders:read. The other authority, FACTOR_BEARER, is new in Spring Security 7: it records how the user authenticated (with a bearer token), so rules can demand several factors (multi-factor authentication). No session and no database: everything came from the token.
  4. The same token at /admin/stats is 403: it's valid, but it has no admin scope.
  5. Changing one character (${TOKEN}x) breaks the signature: 401, and the WWW-Authenticate: Bearer error="invalid_token"… header says why (Invalid signature). Nobody can forge or edit a token without the key. The header also points to /.well-known/oauth-protected-resource, the OAuth protected-resource metadata (RFC 9728) that tells clients where to get a token.
  6. With a real identity provider you'd delete /token, the encoder and the shared secret, and set spring.security.oauth2.resourceserver.jwt.issuer-uri; the provider signs with a private key and Spring verifies with its published public keys.

#Passwords and users

Added

Never store passwords; store slow, salted hashes of them. A fast hash like SHA-256 is the wrong tool: attackers with a leaked table can try billions of guesses per second. Password hashing functions (bcrypt, scrypt, Argon2, PBKDF2) are slow on purpose and use a random salt per password, so the same password gives a different hash each time and precomputed tables are useless.

Spring Security's PasswordEncoder does this, and the recommended one is the delegating encoder: it prefixes each hash with its algorithm, like {bcrypt}$2a$10$…, so you can move to a stronger algorithm later while old hashes still verify. Your users come from a UserDetailsService: in memory for demos, normally your own users table.

src/main/java/com/example/shop/Passwords.java
package com.example.shop;

import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
class Passwords implements CommandLineRunner {
    @Override
    public void run(String... args) {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        String first = encoder.encode("rohit-pass");
        String second = encoder.encode("rohit-pass");

        System.out.println("starts with: " + first.substring(0, 14));
        System.out.println("length: " + first.length());
        System.out.println("same hash twice? " + first.equals(second));
        System.out.println("right password matches? " + encoder.matches("rohit-pass", first));
        System.out.println("wrong password matches? " + encoder.matches("rohit-pas", first));
        System.out.println("old SHA-256 hash still verifies? " + encoder.matches("rohit-pass",
                "{sha256}" + new org.springframework.security.crypto.password.StandardPasswordEncoder().encode("rohit-pass")));
    }
}
pom.xml
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
starts with: {bcrypt}$2a$10
length: 68
same hash twice? false
right password matches? true
wrong password matches? false
old SHA-256 hash still verifies? true
What’s happening
  1. createDelegatingPasswordEncoder() encodes new passwords with bcrypt and marks them {bcrypt}. The rest is bcrypt's own format: $2a$ (the version), 10$ (the cost: 2¹⁰ rounds), then the salt and hash.
  2. The whole string is 68 characters: the 8-character {bcrypt} prefix plus bcrypt's 60.
  3. Encoding the same password twice gives different hashes, because each gets a fresh random salt stored inside the hash. So you can't compare hashes with equals; you call matches(raw, stored), which re-hashes the raw password with the stored salt.
  4. The right password matches, a one-letter typo doesn't.
  5. The last line verifies a hash made by an old, deprecated SHA-256 encoder, stored with a {sha256} prefix. The delegating encoder picks the algorithm from the prefix, so a legacy table keeps working while new and changed passwords are stored as bcrypt: the migration path is built in.
AdvancedTip: hashing cost and identity providers

#CORS and CSRF for APIs

Added

Two browser protections that confuse everyone, because they sound alike and solve opposite problems:

  • CORS (cross-origin resource sharing) is about reading. A browser won't let JavaScript on https://shop-ui.example read a response from https://api.example unless the API says that origin is allowed, through Access-Control-Allow-Origin headers (with a "preflight" OPTIONS request first for non-simple requests). It protects users' data from other sites' scripts. A React or Angular app on a different origin than its API needs CORS configured on the API.
  • CSRF (cross-site request forgery) is about sending. If your API authenticates with a cookie, the browser attaches that cookie to any request to your domain, even one triggered by a form on an attacker's page. CSRF protection requires a token that the attacker's page can't know. Spring Security enables it by default.

The practical rule: an API that authenticates with Authorization headers (Basic or bearer tokens) and no cookies doesn't need CSRF protection, because browsers never attach those headers automatically, so it's normal to disable it there, as the examples above did. An app that uses session cookies must keep it on (Security 7 adds csrf.spa() for single-page apps).

pom.xml
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
src/main/java/com/example/shop/WebSecurity.java
package com.example.shop;

import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
class WebSecurity {

    @Bean
    SecurityFilterChain chain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
                .cors(Customizer.withDefaults());
        return http.build();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(List.of("https://shop-ui.example"));
        config.setAllowedMethods(List.of("GET", "POST"));
        config.setAllowedHeaders(List.of("Content-Type", "Authorization"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}

@RestController
class CartController {
    @GetMapping("/cart")
    String cart() {
        return "2 items";
    }

    @PostMapping("/cart")
    String add() {
        return "added";
    }
}
Terminal
$ curl -si localhost:8080/cart -H "Origin: https://shop-ui.example" | grep -E "^(HTTP|Access-Control-Allow-Origin)"
HTTP/1.1 200 
Access-Control-Allow-Origin: https://shop-ui.example
$ curl -si localhost:8080/cart -H "Origin: https://evil.example" | grep -E "^(HTTP|Access-Control-Allow-Origin)"
HTTP/1.1 403
$ curl -si -X OPTIONS localhost:8080/cart -H "Origin: https://shop-ui.example" -H "Access-Control-Request-Method: POST" | grep -E "^(HTTP|Access-Control)"
HTTP/1.1 200 
Access-Control-Allow-Origin: https://shop-ui.example
Access-Control-Allow-Methods: GET,POST
$ curl -s -o /dev/null -w "%{http_code}\n" -X POST localhost:8080/cart
403
What’s happening
  1. cors(Customizer.withDefaults()) tells Spring Security to use the CorsConfigurationSource bean: one allowed origin, GET and POST, and two request headers.
  2. A request from the allowed origin gets Access-Control-Allow-Origin: https://shop-ui.example, so a browser would let that page's JavaScript read the response.
  3. From https://evil.example the answer is 403 with no CORS header: Spring rejects cross-origin requests from origins that aren't allowed. (A browser would block the read anyway; note that curl, not being a browser, is never stopped by CORS itself.)
  4. The preflight OPTIONS request, which browsers send before a cross-origin POST with JSON, gets 200 and the allowed origin and methods.
  5. This chain left CSRF protection on (the default), so a POST without a CSRF token is refused with 403, even though every request is permitted. That's the protection doing its job for cookie-based apps; for a token-based API you'd disable it as in Securing an API.

#Actuator: health, info and metrics

Added

Spring Boot Actuator adds operational endpoints under /actuator: health checks for load balancers and Kubernetes, build and app info, metrics, the current configuration, loggers you can change at run time, thread dumps. By default only health is exposed over HTTP; you choose the rest with management.endpoints.web.exposure.include, and you secure them, because env and heapdump reveal a lot.

Two health groups are on by default since Boot 4, built for Kubernetes probes:

  • liveness (/actuator/health/liveness): "is the process alive, or should it be restarted?"
  • readiness (/actuator/health/readiness): "can it take traffic now?" (it's OUT_OF_SERVICE during startup and while shutting down).
src/main/java/com/example/shop/HelloController.java
package com.example.shop;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
class HelloController {
    @GetMapping("/hello")
    String hello() {
        return "Hello";
    }
}
src/main/resources/application.properties
spring.application.name=shop
management.endpoints.web.exposure.include=health,info,metrics
management.endpoint.health.show-details=always
management.info.env.enabled=true
info.app.name=Shop API
info.app.team=Checkout
Terminal
$ curl -s localhost:8080/actuator | grep -o '"[a-z-]*":{"href' | cut -d'"' -f2 | sort | tr '\n' ' '
health health-path info metrics self
$ curl -s localhost:8080/actuator/health/liveness
{"status":"UP"}
$ curl -s localhost:8080/actuator/health/readiness
{"status":"UP"}
$ curl -s localhost:8080/actuator/health | grep -o '"db":{"details":{[^}]*},"status":"[A-Z]*"'
"db":{"details":{"database":"H2","validationQuery":"isValid()"},"status":"UP"
$ curl -s localhost:8080/actuator/info
{"app":{"name":"Shop API","team":"Checkout"}}
$ curl -s localhost:8080/hello > /dev/null && curl -s "localhost:8080/actuator/metrics/http.server.requests?tag=uri:/hello" | grep -o '"statistic":"COUNT","value":[0-9.]*'
"statistic":"COUNT","value":1.0
What’s happening
  1. exposure.include=health,info,metrics exposes three endpoints. The /actuator index lists them as links (plus self and health-path, the link template for sub-paths like health/liveness).
  2. Liveness and readiness are both UP: the app is alive and accepting traffic. In Kubernetes you'd point the livenessProbe and readinessProbe at these two URLs.
  3. show-details=always makes /actuator/health list each component (db, diskSpace, ping, the two probe states, ssl). Because the starter has a data source, the db check asks the H2 connection isValid(): UP. (In production you'd show details only to authorised users.)
  4. /actuator/info returns the info.* properties, {"app":{"name":"Shop API","team":"Checkout"}}, once management.info.env.enabled is on. Build info (version, time) and Git info can be added by the build plugins.
  5. Every HTTP request is timed by Micrometer under the http.server.requests metric, tagged by URI, method and status. After one call to /hello, its count is 1.0.

#Logging

Added

Spring Boot logs through SLF4J (the API you code against) with Logback as the default implementation underneath, so LoggerFactory.getLogger(MyClass.class) is the line you'll see at the top of classes. The pattern is like Node's pino or winston: named loggers, levels (TRACE, DEBUG, INFO, WARN, ERROR), configured centrally rather than in code.

Three things worth knowing:

  • Levels per package, from properties: logging.level.com.example.shop=debug, logging.level.org.hibernate.SQL=debug. Change them at run time through Actuator's loggers endpoint.
  • Placeholders, not concatenation: log.info("Order {} placed", id) only builds the message if INFO is enabled.
  • Structured logging (Boot 3.4+): logging.structured.format.console=ecs (or logstash, gelf) writes one JSON object per line, ready for Elasticsearch, Datadog or CloudWatch to index.
  • MDC (mapped diagnostic context): per-thread key-values such as a request id that every log line on that request carries.
src/main/java/com/example/shop/OrderLog.java
package com.example.shop;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
class OrderLog implements CommandLineRunner {
    private static final Logger log = LoggerFactory.getLogger(OrderLog.class);

    @Override
    public void run(String... args) {
        MDC.put("orderId", "ORD-1001");
        try {
            log.debug("Validating cart");
            log.info("Order placed for {} items", 3);
            log.warn("Stock low for {}", "KB-1");
        } finally {
            MDC.remove("orderId");
        }
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
logging.level.com.example.shop=info
logging.structured.format.console=ecs
Terminal
$ ./mvnw -q spring-boot:run | grep OrderLog
{"@timestamp":"2026-11-26T15:42:55.175833Z","log":{"level":"INFO","logger":"com.example.shop.OrderLog"},"process":{"pid":41033,"thread":{"name":"main"}},"service":{"name":"shop"},"message":"Order placed for 3 items","orderId":"ORD-1001","ecs":{"version":"8.11"}}
{"@timestamp":"2026-11-26T15:42:55.176269Z","log":{"level":"WARN","logger":"com.example.shop.OrderLog"},"process":{"pid":41033,"thread":{"name":"main"}},"service":{"name":"shop"},"message":"Stock low for KB-1","orderId":"ORD-1001","ecs":{"version":"8.11"}}
What’s happening
  1. The logger is named after the class (com.example.shop.OrderLog), and logging.level.com.example.shop=info sets that package to INFO, while the root stays at WARN. (The main class is in the same package, so its three startup lines print too; grep OrderLog keeps just this example's lines.)
  2. So debug("Validating cart") is dropped, and the INFO and WARN lines print. {} placeholders are filled from the arguments: Order placed for 3 items, Stock low for KB-1.
  3. With logging.structured.format.console=ecs, each line is one JSON object in Elastic Common Schema: @timestamp, log.level, process.pid and the thread name, service.name (from spring.application.name), log.logger, the message and the ECS version. A log platform indexes each field, so you can search log.level:WARN AND service.name:shop instead of grepping text.
  4. MDC.put("orderId", …) attached "orderId":"ORD-1001" to every line logged on this thread until MDC.remove. In a web app you'd set a request id in a filter so every line of a request can be found together.

#Observability: metrics and tracing

Added

Observability means being able to answer "what is the service doing, and why is it slow?" from the outside, through three signals: logs (above), metrics (numbers over time: requests per second, error rate, latency percentiles, JVM memory) and traces (one request followed across services, with a timed span per step).

Spring Boot uses Micrometer for metrics and tracing: a vendor-neutral facade, like SLF4J for metrics, with registries for Prometheus, Datadog, OTLP and others. Boot instruments a lot for you (HTTP requests, JDBC pools, JVM, caches), and you add business metrics with a MeterRegistry. For tracing, Boot 4 adds a spring-boot-starter-opentelemetry that exports traces and metrics over OTLP. A typical setup: Prometheus scrapes /actuator/prometheus, Grafana draws dashboards and alerts, and traces go to Tempo, Jaeger or a vendor.

Add this to pom.xml:

pom.xml
		<dependency>
			<groupId>io.micrometer</groupId>
			<artifactId>micrometer-registry-prometheus</artifactId>
		</dependency>
src/main/java/com/example/shop/OrderController.java
package com.example.shop;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
class OrderController {

    private final MeterRegistry registry;

    OrderController(MeterRegistry registry) {
        this.registry = registry;
    }

    @PostMapping("/orders")
    String place(@RequestParam String payment) {
        Counter.builder("shop.orders.placed")
                .description("Orders placed")
                .tag("payment", payment)
                .register(registry)
                .increment();
        return "placed";
    }
}
src/main/resources/application.properties
spring.application.name=shop
management.endpoints.web.exposure.include=health,prometheus
Terminal
$ curl -s -X POST "localhost:8080/orders?payment=card" && curl -s -X POST "localhost:8080/orders?payment=card" && curl -s -X POST "localhost:8080/orders?payment=paypal" && echo
placedplacedplaced
$ curl -s localhost:8080/actuator/prometheus | grep shop_orders
# HELP shop_orders_placed_total Orders placed
# TYPE shop_orders_placed_total counter
shop_orders_placed_total{payment="card"} 2.0
shop_orders_placed_total{payment="paypal"} 1.0
$ [ $(curl -s localhost:8080/actuator/prometheus | grep -c '^jvm_') -gt 40 ] && echo "more than 40 jvm_ lines"
more than 40 jvm_ lines
$ curl -s localhost:8080/actuator/prometheus | grep -o '^jvm_memory_used_bytes' | head -1
jvm_memory_used_bytes
What’s happening
  1. Adding the Prometheus registry makes Boot create a Prometheus-format MeterRegistry and an /actuator/prometheus endpoint (exposed here).
  2. The controller counts orders with a counter named shop.orders.placed, tagged with the payment method. Tags (labels, in Prometheus terms) let dashboards split one metric by dimension. Three orders: two by card, one by PayPal.
  3. The Prometheus endpoint renames it in Prometheus style, shop_orders_placed_total, with # HELP and # TYPE counter lines and one series per tag value: payment="card" is 2.0, payment="paypal" is 1.0. Prometheus would scrape this URL every few seconds and compute rates.
  4. You didn't write any JVM metrics, yet the same endpoint has dozens of lines starting jvm_ (the exact number varies a little between runs, as memory pools and GC counters appear), such as jvm_memory_used_bytes: memory pools, GC pauses, threads, classes. That's Boot's instrumentation, and it's what you'd graph when hunting a memory leak (chapter 10).
AdvancedTip: keep metric tags bounded

#Packaging and running in production

Added

A Spring Boot service ships as the executable JAR from chapter 11, almost always inside a container image. You have two good options:

  • Buildpacks: ./mvnw spring-boot:build-image builds an OCI image with no Dockerfile at all, using Paketo buildpacks (Boot 4.2 defaults to an Ubuntu 26.04 builder). It picks a JRE, uses the JAR's layers, and sets sensible memory flags. Needs Docker; not run here.
  • A Dockerfile you control, using the layered JAR: extract the layers in a build stage and copy them in order from least to most frequently changed, so a code change rebuilds only the small application layer.

Whichever you pick, production behaviour comes from configuration, not code: environment variables for settings and secrets (chapter 12), a memory limit the JVM respects (-XX:MaxRAMPercentage, chapter 10), and graceful shutdown, which is the default in Boot 4 (server.shutdown=graceful): on SIGTERM the server stops accepting new requests, readiness goes OUT_OF_SERVICE, and in-flight requests get up to 30 seconds (spring.lifecycle.timeout-per-shutdown-phase) to finish.

Dockerfile
FROM eclipse-temurin:25-jre AS builder
WORKDIR /build
COPY target/shop-0.0.1-SNAPSHOT.jar app.jar
RUN java -Djarmode=tools -jar app.jar extract --layers --launcher --destination extracted

FROM eclipse-temurin:25-jre
WORKDIR /app
COPY --from=builder /build/extracted/dependencies/ ./
COPY --from=builder /build/extracted/spring-boot-loader/ ./
COPY --from=builder /build/extracted/snapshot-dependencies/ ./
COPY --from=builder /build/extracted/application/ ./
ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75"
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]
src/main/java/com/example/shop/WhereAmI.java
package com.example.shop;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
class WhereAmI implements CommandLineRunner {
    @Override
    public void run(String... args) {
        System.out.println("Java " + Runtime.version().feature() + " on " + System.getProperty("os.name"));
        System.out.println("max heap is 75% of the container's memory limit: "
                + (Runtime.getRuntime().maxMemory() > 700L * 1024 * 1024 && Runtime.getRuntime().maxMemory() <= 768L * 1024 * 1024));
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q -DskipTests package
$ docker build -q -t java-notes-shop . > /dev/null && echo "image built"
image built
$ docker run --rm --memory=1g -e SPRING_MAIN_WEB_APPLICATION_TYPE=none java-notes-shop 2>/dev/null
Java 25 on Linux
max heap is 75% of the container's memory limit: true
$ docker image rm java-notes-shop > /dev/null && echo "image removed"
image removed
What’s happening
  1. package builds the executable JAR. The Dockerfile's first stage extracts it into its four layers with Spring Boot's jarmode=tools (the same layers list-layers showed in chapter 11), plus the launcher.
  2. The second stage starts from a plain JRE image (no compiler needed at run time) and copies the layers in order. Docker caches each COPY as a layer, so when only your code changes, the 79 dependency JARs come from cache. JAVA_TOOL_OPTIONS sets the max heap to 75% of the container's memory instead of the default 25%.
  3. docker run --memory=1g limits the container to 1 GB, and the environment variable SPRING_MAIN_WEB_APPLICATION_TYPE=none (relaxed binding again) makes this one run print and exit instead of serving. Inside, the JVM reports Java 25 on Linux: the same JAR, now in a Linux container.
  4. The JVM read the container's memory limit, not the Mac's: 75% of 1 GB is 768 MB, and the max heap falls in that range, true. (The 2>/dev/null hides the JVM's one-line notice that it picked up JAVA_TOOL_OPTIONS.)
  5. The last line cleans up the image. In a real pipeline, CI builds and pushes the image, and the platform (Kubernetes, ECS, Cloud Run) runs it with probes on the Actuator endpoints and the config from its environment.

#Your turn: security and production

Added
Your turn: an admin-only actuator

Expose health and metrics. Health must stay public (load balancers call it without credentials), but metrics must require a user with the OPS role. Use HTTP Basic with one in-memory user ops / ops-pass.

Show answer
pom.xml
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
src/main/java/com/example/shop/OpsSecurity.java
package com.example.shop;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
class OpsSecurity {

    @Bean
    SecurityFilterChain chain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/actuator/health/**").permitAll()
                        .requestMatchers("/actuator/**").hasRole("OPS")
                        .anyRequest().authenticated())
                .httpBasic(Customizer.withDefaults());
        return http.build();
    }

    @Bean
    UserDetailsService users() {
        var encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        return new InMemoryUserDetailsManager(
                User.withUsername("ops").password(encoder.encode("ops-pass")).roles("OPS").build());
    }
}
src/main/resources/application.properties
spring.application.name=shop
management.endpoints.web.exposure.include=health,metrics
Terminal
$ curl -s localhost:8080/actuator/health
{"groups":["liveness","readiness"],"status":"UP"}
$ curl -s -o /dev/null -w "%{http_code}\n" localhost:8080/actuator/metrics
401
$ curl -s -u ops:ops-pass localhost:8080/actuator/metrics | grep -o '"jvm.memory.used"'
"jvm.memory.used"
What’s happening
  1. Rules are checked in order, so the public health/** rule (which also covers the liveness and readiness sub-paths) must come before the broader /actuator/** rule.
  2. Health answers without credentials, {"groups":["liveness","readiness"],"status":"UP"}. Metrics without credentials is 401.
  3. With the ops user, the metrics list comes back, including jvm.memory.used. In production you might instead move Actuator to a separate management port that isn't reachable from outside (management.server.port).
Your turn: a bcrypt check

Write a runner that hashes s3cret! with the delegating encoder and prints whether matches accepts the right password and rejects S3cret! (capital S). Then explain why printing the hash itself wouldn't make a repeatable test.

Show answer
pom.xml
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
src/main/java/com/example/shop/CheckHash.java
package com.example.shop;

import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.stereotype.Component;

@Component
class CheckHash implements CommandLineRunner {
    @Override
    public void run(String... args) {
        var encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        String stored = encoder.encode("s3cret!");
        System.out.println("right password: " + encoder.matches("s3cret!", stored));
        System.out.println("capital S: " + encoder.matches("S3cret!", stored));
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
right password: true
capital S: false
What’s happening
  1. matches re-hashes the candidate with the salt and cost stored in stored and compares: right password: true, capital S: false (passwords are case-sensitive).
  2. The hash itself changes on every run, because encode generates a new random salt each time. A test that compares hash strings would fail every run; tests must check matches, which is also exactly what login does.

Written fresh, no doc. Examples were run with Eclipse Temurin 25.0.5.1 and Spring Boot 4.2.0 (Maven 3.10.1); facts come from openjdk.org, docs.oracle.com and spring.io, read 2026-11-26.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.