Spring Concepts

Spring Boot, Spring Security, and Spring Batch — core concepts explained in depth.

Sort

Core Spring & Boot

45
Spring Boot

Containerizing Spring Boot: Dockerfiles, Layered JARs & Buildpacks

Packaging a Spring Boot application as an OCI image — the book's hand-written Dockerfile, layered JARs that make Docker's build cache actually work, and spring-boot:build-image as the no-Dockerfile Cloud Native Buildpacks alternative.

46
Spring Boot

Customizing Spring Boot Actuator: Info, Health, Metrics & Security

Extend Actuator past its built-in endpoints: contribute application data to /info with InfoContributor, write a HealthIndicator that reflects a real dependency, publish business metrics through Micrometer's MeterRegistry, build custom endpoints with @Endpoint, and lock the whole surface down with Spring Security and EndpointRequest.

47
Spring Boot🔬 Lab

Spring Boot Actuator: Built-in Endpoints

Actuator adds production-readiness endpoints to a Spring Boot app — /health, /info, /metrics, /env, /beans, /mappings & more — over HTTP and JMX, plus how to expose and consume them safely.

57
Spring Boot

Dependency Injection: From EJB to Jakarta CDI

How container-managed dependency injection evolved from EJB's XML deployment descriptors to the formal Jakarta CDI specification, and why @Autowired/@Component and @Inject/@Named are two dialects of the same underlying model in Spring and Quarkus.

69
Spring Boot🔬 Lab

Environment-Specific Configuration with Spring Profiles

How Spring profiles let different properties and beans apply depending on which profile is active, why setting spring.profiles.active outside of application.yml keeps environment-specific config properly separated, and how the book's multi-document spring.profiles: prod YAML syntax has since been replaced by spring.config.activate.on-profile.

72
Spring Boot🔬 Lab

Creating Your Own Configuration Properties with @ConfigurationProperties

How @ConfigurationProperties turns any bean's setters into configuration-driven values, why extracting them into a dedicated holder bean keeps controllers and services clean, and how to generate IDE metadata for custom properties — plus why records with constructor binding are now the preferred alternative to a mutable, Lombok-backed holder class.

75
Spring Boot🔬 Lab

Fine-Tuning Autoconfiguration with Spring Boot Configuration Properties

How the Spring environment abstraction aggregates properties from JVM system properties, OS environment variables, command-line arguments, and application.yml/properties into one source, and how a few hundred built-in configuration properties (server.port, spring.datasource.*, logging.level.*) let you tune Spring Boot's autoconfigured beans without writing a single @Bean method.

90
Spring Boot

The Spring Framework Landscape

How the core Spring Framework, Spring Boot, Spring Data, Spring Security, Spring Batch/Integration, and Spring Cloud fit together as one ecosystem, and how that landscape has shifted since 2019 (Jakarta EE namespace, GraalVM native images, Spring Cloud's current sub-projects).

93
Spring Boot🔬 Lab

Spring Boot Autoconfiguration

How @SpringBootApplication, starter dependencies, and conditional beans let Spring Boot wire an application with almost no explicit configuration.

Spring MVC & Web

6
Spring Boot

OpenAPI Generator: Contract-First Code Generation with the Maven Plugin

How the openapi-generator-maven-plugin turns an OpenAPI spec into Spring controller interfaces and DTOs during the build, using generatorName=spring, library selection, and interfaceOnly plus the delegate pattern to keep hand-written logic out of generated code.

55
Spring Boot

Consuming REST Services: RestTemplate & Traverson

Calling REST APIs from a Spring application — RestTemplate's per-verb operations for GET/PUT/DELETE/POST and Traverson's relation-name navigation of a hypermedia API, plus where RestClient now fits.

56
Spring Boot

DispatcherServlet Internals: Handler Mapping, Adapters, and Message Converters

The concrete pipeline behind a REST controller call — RequestMappingHandlerMapping matching a route via PathPattern, HandlerAdapter resolving arguments and invoking the method via reflection, and HttpMessageConverter handling JSON (de)serialization on both sides.

60
Spring Boot🔬 Lab

Spring Data REST: Repositories as Hypermedia APIs

How adding spring-boot-starter-data-rest exposes every Spring Data repository as a hypermedia REST API with zero controller code, how @RepositoryRestResource and @RestResource adjust paths and exposure, and how the book's ResourceProcessor became today's RepresentationModelProcessor for adding custom links.

63
Spring Boot

Enabling Hypermedia: Spring HATEOAS and the _links/_embedded Shape

How Spring HATEOAS attaches self-describing hyperlinks to REST responses so clients navigate an API by relation name instead of hardcoded URLs, via RepresentationModel/EntityModel/CollectionModel, linkTo(methodOn(...)) link builders, and RepresentationModelAssembler classes that produce the HAL _links/_embedded JSON shape.

66
Spring Boot🔬 Lab

Writing RESTful Controllers with Spring MVC

How @RestController and the HTTP-method mapping annotations (@GetMapping/@PostMapping/@PutMapping/@PatchMapping/@DeleteMapping) map CRUD operations onto REST endpoints, why PUT and PATCH have genuinely different replace-vs-merge semantics that the annotations alone don't enforce, and how Spring Framework 6's ProblemDetail (RFC 7807) now gives 404s and other error responses a structured body instead of an empty one.

84
Spring Boot🔬 Lab

Spring MVC Form Validation with the Bean Validation API

How to declare validation rules with Bean Validation annotations on a domain class and enforce them at form-binding time with @Valid and Errors/BindingResult, and why spring-boot-starter-validation is now a separate, explicit dependency instead of a transitive one.

87
Spring Boot🔬 Lab

Spring MVC Request Handling and Data Binding

How a Spring MVC controller pairs @GetMapping/@PostMapping handlers with a Model to render views and with implicit command-object binding to process form submissions, and how Java records now offer a dependency-free alternative to Lombok for immutable domain types.

Data Access

1
Spring Boot

JPQL IN Clause Limits and Loading by Multiple Primary Keys

Why databases such as Oracle reject a JPQL or SQL IN clause once it holds more than 1000 elements, and the three ways around it: splitting the values into batches yourself, rewriting the filter as a sub-select, or, when filtering by primary key specifically, using Hibernate's MultiIdentifierLoadAccess (byMultipleIds) to fetch many entities by id in one call without hand-rolling the batching.

2
Spring Boot

Ordering Inserts and Updates to Avoid Deadlocks

How hibernate.order_inserts and hibernate.order_updates make Hibernate group and reorder pending INSERT/UPDATE statements at flush time so operations against the same table happen in a consistent order across transactions, reducing (not eliminating) deadlocks on multi-node clusters such as Galera, and why avoiding explicit locking is still the first recommendation before reaching for these settings.

3
Spring Boot

Hibernate's First-Level and Second-Level Cache

Why em.find() and traversing a to-one association can be served entirely from the first-level (and second-level) cache while a JPQL, Criteria, or native query always hits the database, with Hibernate discarding a row from the result set and substituting the already-managed instance whenever the first-level cache already holds that entity; caching an actual query result requires the separate Query Cache, not the entity caches.

4
Spring Boot

Calling Stored Procedures from JPA

How @NamedStoredProcedureQuery maps a database stored procedure into JPA using @StoredProcedureParameter entries for IN, OUT, INOUT, and REF_CURSOR parameters, why a stored procedure query must be run with execute() instead of getResultList()/getSingleResult(), and how getOutputParameterValue() retrieves each output parameter afterward.

5
Spring Boot

JPQL, Criteria API, and Native Queries: Choosing the Right Query Approach

Why JPA gives you three distinct query APIs instead of one: JPQL is a string-based query language over your entity model (database-independent, but limited to the feature set Hibernate can translate to SQL), Criteria API exposes that same feature set as a type-safe Java API worth its verbosity mainly when a query has to be built dynamically from user input, and native SQL queries bypass the abstraction entirely for full access to database-specific features at the cost of portability; all three protect against SQL injection equally, but only if you use bind parameters instead of string concatenation.

78
Spring Boot🔬 Lab

Persisting Data with Spring Data JPA Repositories

How annotating domain classes as JPA entities and extending CrudRepository gives you a working persistence layer with zero implementation code, and how Spring Data parses derived query method names (findByDeliveryZip, readOrdersByDeliveryZipAndPlacedAtBetween) into real queries, with @Query as the escape hatch.

81
Spring Boot🔬 Lab

Spring JDBC Persistence with JdbcTemplate and SimpleJdbcInsert

How JdbcTemplate eliminates JDBC's connection/statement/result-set boilerplate via query()/queryForObject() and a RowMapper, how SimpleJdbcInsert simplifies inserts that need a generated key, and how schema.sql/data.sql auto-initialize a database on startup — plus why Spring Framework 6.1's JdbcClient is now the recommended fluent facade for the same job.

Reactive

Messaging

Spring Security

7
Spring Security

Testing Authorization, CSRF, and CORS with spring-security-test

How to assert Spring Security configuration in tests: method security (@PreAuthorize/@PostAuthorize/@PreFilter/@PostFilter) is tested without MockMvc by injecting the protected bean, calling it under @WithMockUser, and asserting AuthenticationException for no principal versus AccessDeniedException for the wrong authority; CSRF is tested with SecurityMockMvcRequestPostProcessors.csrf() plus its asHeader() and useInvalidToken() variants, where the valuable test is the token-less POST asserting 403; CORS is tested by hand-rolling the browser preflight as an OPTIONS request carrying Origin and Access-Control-Request-Method and asserting the Access-Control-Allow-Origin/Allow-Methods response headers — all depending on the security filter chain actually being wired into MockMvc via @AutoConfigureMockMvc or SecurityMockMvcConfigurers.springSecurity(); book vs. today, the test code is largely unchanged — @EnableGlobalMethodSecurity became @EnableMethodSecurity, interceptors now throw AuthorizationDeniedException (extends AccessDeniedException since 6.3, so existing assertions still pass), csrf() is untouched despite the 6.0 XOR/BREACH masking default underneath it, preflight-by-hand remains the only CORS approach, and the book's expected wildcard origin no longer holds under allowedOriginPatterns, which echoes the matched origin instead.

8
Spring Security🔬 Lab

Spring Security Testing: Mock Users and Authentication

How spring-security-test establishes a principal for a test — @WithMockUser fabricating a UserDetails with no lookup (roles auto-prefixed ROLE_, authorities not, usable at class level and overridable per-method with @WithAnonymousUser), @WithUserDetails loading a real user through a UserDetailsService bean so the principal is your own implementation, and a custom annotation wired to a WithSecurityContextFactory via @WithSecurityContext when the concrete Authentication type matters — all three skipping authentication entirely, which is why the AuthenticationProvider/PasswordEncoder/success-and-failure-handler path must be driven separately through MockMvc with httpBasic() or the formLogin() request builder plus the authenticated()/unauthenticated() result matchers; the book's JUnit 4 era idiom is now @ExtendWith(SpringExtension.class)/@SpringJUnitConfig (implied by @SpringBootTest), and springSecurity() is applied automatically under Spring Boot but still explicit via .apply(springSecurity()) outside it.

9
Spring Security

Keycloak as the Authorization Server for a Spring Resource Server

How a Spring Boot resource server plugs into Keycloak as a real, off-the-shelf authorization server — configuring a realm, client, client scope, users and roles in the admin console, obtaining a JWT from the token endpoint, using protocol mappers to add roles/username/audience claims, and validating that JWT offline against the realm's JWKS endpoint (kid-based key selection, so key rotation works) while enforcing rules at three layers (hasAuthority at the endpoint, @PreAuthorize on the service, a SpEL-filtered @Query in the repository); Keycloak is still very much alive but the book's every mechanism has moved — the WildFly runtime was replaced by Quarkus in Keycloak 17 (bin/kc.sh instead of standalone.sh, and /auth dropped from every URL so the issuer is now /realms/{realm}), the master realm is admin-only, the password grant is disabled by default for new clients since 26.2, Keycloak's own keycloak-spring-boot-starter adapter was deprecated and removed, and the Spring Security OAuth classes it used (@EnableResourceServer, JwkTokenStore) are EOL — today the whole configuration collapses to spring-boot-starter-oauth2-resource-server plus issuer-uri/audiences, with a JwtAuthenticationConverter mapping Keycloak's native realm_access.roles and preferred_username claims instead of reshaping the realm to fit a dead library.

10
Spring Security

Method Security Filtering: @PreFilter, @PostFilter, and Spring Data

@PreFilter and @PostFilter apply a SpEL rule per element (filterObject vs. authentication) to trim a collection argument or return value in place rather than allowing or denying the whole call the way @PreAuthorize/@PostAuthorize do — requiring a mutable collection, since the aspect mutates the caller's instance and an immutable List.of() throws UnsupportedOperationException; both annotations are unchanged today apart from swapping the deprecated @EnableGlobalMethodSecurity(prePostEnabled = true) for @EnableMethodSecurity, and the book's chapter 17.3 technique of replacing repository-level @PostFilter with a SecurityEvaluationContextExtension bean plus a ?#{authentication.name} predicate inside @Query remains the officially documented recommendation, since in-memory filtering wastes the heap and breaks pagination.

11
Spring Security

Method Security: Preauthorization and Postauthorization

Method security moves authorization from the filter chain onto the method call itself via a Spring AOP interceptor, where @PreAuthorize evaluates a SpEL rule before invocation (using hasAuthority/hasRole plus method arguments via #paramName and the current authentication) and @PostAuthorize evaluates it after, against the special returnObject, with hasPermission() delegating object-level logic to a PermissionEvaluator bean; today the book's @EnableGlobalMethodSecurity(prePostEnabled = true) is deprecated in favor of @EnableMethodSecurity (since 5.6), which turns pre/post annotations on by default, replaces the voter stack with AuthorizationManager-based interceptors and a deferred Supplier<Authentication>, and notably no longer auto-detects a custom PermissionEvaluator — it must be wired through a static MethodSecurityExpressionHandler bean or every hasPermission() silently denies.

12
Spring Security

JWT Signing: Symmetric vs. Asymmetric Keys

How a resource server validates a JWT locally by checking its signature: symmetric HMAC (HS256) where one shared secret both signs and verifies — so every resource server holding it can also mint tokens — versus an asymmetric RSA key pair (RS256) where the authorization server signs with a private key and any number of resource servers verify with a freely publishable public key, plus adding and reading custom claims; the book's Spring Security OAuth JwtTokenStore/JwtAccessTokenConverter/TokenEnhancer stack is end-of-life and maps today onto Nimbus-backed JwtEncoder/JwtDecoder, OAuth2TokenCustomizer, and Jwt.getClaim(), while its ad-hoc /oauth/token_key public-key endpoint is exactly what the standard JWK Set endpoint (RFC 7517, discovered via the jwks_uri of RFC 8414; /oauth2/jwks in Spring Authorization Server) formalizes, adding kid-based key rotation the book's static PEM config cannot do.

13
Spring Security

OAuth 2 Resource Server: Remote Check, Blackboarding, and Local Validation

The resource server must validate a bearer token it never issued and (with opaque UUID tokens) cannot read, which yields exactly three strategies — calling the authorization server's check_token endpoint per request, blackboarding via a JdbcTokenStore-backed database shared by both servers, or verifying a signature locally — traded off on per-request latency, availability coupling, and revocation lag; today the book's @EnableResourceServer/ResourceServerConfigurerAdapter/TokenStore API is end-of-life, the remote check is standardized as RFC 7662 introspection configured with oauth2ResourceServer(...).opaqueToken() (or three spring.security.oauth2.resourceserver.opaquetoken.* properties), local validation is .jwt() with NimbusJwtDecoder fetching the JWK set lazily so startup isn't coupled to the IdP, and blackboarding has no supported successor — JdbcTokenStore was never ported (issue #9381 closed as duplicate) and survives only as a custom OpaqueTokenIntrospector, whose javadoc blesses querying a backing store, best used to cache introspection responses rather than to share a schema between the two servers.

14
Spring Security

Implementing an OAuth2 Authorization Server: From Spring Security OAuth to Spring Authorization Server

Building the component that issues access tokens — the book does it with the now-archived Spring Security OAuth project's @EnableAuthorizationServer + ClientDetailsService, end-of-lifed in 2022 and replaced by the standalone Spring Authorization Server (RegisteredClient/RegisteredClientRepository/AuthorizationServerSettings beans), which itself was folded back into Spring Security as of Spring Security 7.0; of the book's four grant types, only authorization-code and client-credentials survive directly in the modern project — password is unsupported entirely (never implemented, deprecated in OAuth 2.1) and refresh-token support is automatic rather than separately configured.

15
Spring Security

Implementing an OAuth2 Client: Single Sign-On with ClientRegistration

Building the smallest OAuth2 actor — a client app that redirects to somebody else's authorization server, exchanges the returned code for a token, and reads the user's details, with no users, tokens, or protected resources of its own — modeled by Spring Security as ClientRegistration (one client's registration at one provider), ClientRegistrationRepository, and the oauth2Login() HttpSecurity method that autoconfigures almost everything from a handful of spring.security.oauth2.client.registration.* properties; the API (ClientRegistration, OAuth2AuthenticationToken, OidcUser) is largely unchanged since 2020, with the main shifts being the lambda-DSL SecurityFilterChain replacing WebSecurityConfigurerAdapter and authorizeHttpRequests() replacing authorizeRequests().

16
Spring Security

OAuth 2 Fundamentals and Grant Types

The OAuth 2 mental model — resource owner, client with its own client_id/client_secret, authorization server, and resource server exchanging scope-limited access tokens — plus when to pick each grant type (authorization code's two round trips and why, password, client credentials, refresh token) and the book's own "sins of OAuth 2"; note that since 2020 the password grant has become forbidden rather than merely discouraged (RFC 9700/BCP 240 says MUST NOT, OAuth 2.1 omits it, AuthorizationGrantType.PASSWORD is deprecated in Spring Security 6.x and gone in 7.0, and Spring Authorization Server never supported it) while PKCE moved from an optional hardening note to mandatory for every authorization-code client, alongside exact redirect-URI matching and no bearer tokens in query strings.

17
Spring Security

Hand-Rolled Token Authentication: The Pre-OAuth2 Case Study

A hands-on two-server build (an authentication server that owns credentials and issues one-time tokens, a business-logic server that trusts a bearer token on every request with no server-side session) expressed entirely in Spring Security's own contracts (Authentication, AuthenticationProvider, OncePerRequestFilter, SecurityContextHolder) — deliberately pre-OAuth2 pedagogy showing what a bearer-token flow has to do before the framework hands you OAuth2/OIDC to do it in a standardized way; the book's javax-era filter and WebSecurityConfigurerAdapter config map to jakarta.servlet + a SecurityFilterChain bean today, and production systems now reach for Spring Authorization Server (RegisteredClient/JWT) instead of hand-rolling this exact mechanism, though the underlying contracts this concept teaches are unchanged.

18
Spring Security🔬 Lab

CORS: Same-Origin Policy, Preflight, and @CrossOrigin vs http.cors()

CORS is a browser mechanism that relaxes the same-origin policy rather than a server-side restriction — an unconfigured cross-origin call still executes on the server and only its response is withheld from JavaScript — configured either per endpoint with Spring MVC's @CrossOrigin or centrally via http.cors() plus a CorsConfigurationSource whose CorsFilter must run before Spring Security's authentication and authorization so credential-less preflight OPTIONS requests are not rejected with 401; the book's WebSecurityConfigurerAdapter.configure(HttpSecurity) container is now a SecurityFilterChain bean and the raw lambda source a UrlBasedCorsConfigurationSource bean, while CorsConfiguration, @CrossOrigin, and http.cors() themselves are unchanged, with today's additions being originPatterns (required instead of the wildcard once allowCredentials is true), preFlightRequestHandler, and the WHATWG Fetch Standard superseding the W3C CORS spec the book cites for simple-request rules.

19
Spring Security🔬 Lab

CSRF Protection: CsrfFilter, CsrfTokenRepository, and Practical Customization

CsrfFilter sits in the filter chain, lets GET/HEAD/TRACE/OPTIONS through untouched and demands a token (handed to the client earlier via a CsrfTokenRepository) for every other method, so a fresh Spring Security project rejecting an authenticated POST with 403 is CSRF protection working as designed, not a bug — the fix is passing the token back (hidden form field for server-rendered apps, a cookie via CookieCsrfTokenRepository for SPAs) or, when genuinely appropriate, excluding specific request matchers or disabling it for bearer-token-only APIs; since Spring Security 6.1 the default handler for reading the token became XorCsrfTokenRequestAttributeHandler (BREACH-resistant, deferred token loading) in place of the book's simpler default.

20
Spring Security

Custom Filters in the Spring Security Filter Chain

Spring Security's HttpSecurity exposes exactly three placements for a custom Filter relative to a known built-in filter — addFilterBefore() to reject bad requests before expensive authentication runs, addFilterAfter() to observe what already got through, and addFilterAt() to substitute your own implementation of a responsibility a built-in filter normally owns (note: addFilterAt does NOT remove the filter it sits next to, both still run) — plus the catalog of filters Spring Security ships; the book's javax.servlet.Filter and WebSecurityConfigurerAdapter.configure(HttpSecurity) override are now jakarta.servlet.Filter (Spring Boot 3.0+ Jakarta EE namespace) and a SecurityFilterChain bean using the same three builder methods.

59
Spring Security

Spring Security Authorization: Regex Matchers as the Last Resort

How regexMatchers() matches a request's full path against a regular expression when MVC and Ant matchers can't express the rule — such as a condition spanning two path variables at once — and why the book's own advice to prefer readable matchers still applies today via the still-current, explicit RegexRequestMatcher.

61
Spring Security

Spring Security Authorization: Ant Matchers and the Trailing-Slash Gotcha

How antMatchers() shares its wildcard syntax with mvcMatchers() but matches only the literal path expression, why that leaves a path like /hello/ unprotected when a rule is written for /hello, and why requestMatchers() and Spring's own trailing-slash matching default have both moved since the book's recommendation to prefer MVC matchers.

65
Spring Security🔬 Lab

Spring Security: Selecting Requests with Matcher Methods

How Spring Security's matcher methods (anyRequest(), mvcMatchers()/requestMatchers()) select which requests an authorization rule applies to, why rule order must go from specific to general, how to combine a path with an HTTP method, and why the book's own security argument for preferring MVC matchers over Ant matchers is now built into requestMatchers() by default.

68
Spring Security🔬 Lab

Spring Security Authorization: Authorities and Roles

How Spring Security decides, after authentication succeeds, whether a request is actually allowed — via the GrantedAuthority contract, the hasAuthority()/hasAnyAuthority() methods for fine-grained authorities, hasRole()/hasAnyRole() and the ROLE_ prefix convention for coarser-grained roles, and denyAll() for blanket restrictions — plus the access() method's escape hatch into raw SpEL for anything the named methods can't express.

71
Spring Security🔬 Lab

Spring Security: HTTP Basic and Form-Based Login Authentication

How httpBasic() and formLogin() configure Spring Security's two built-in authentication methods, how AuthenticationEntryPoint/AuthenticationSuccessHandler/AuthenticationFailureHandler customize their failure and success behavior, and how the two methods can run side by side on the same application.

74
Spring Security

Spring Security: SecurityContext Storage and Thread Propagation

How SecurityContextHolder stores the Authentication after login via three strategies (MODE_THREADLOCAL, MODE_INHERITABLETHREADLOCAL, MODE_GLOBAL), and how DelegatingSecurityContextCallable/ExecutorService propagate the security context to self-managed threads the framework doesn't know about.

77
Spring Security

Spring Security: the Authentication and AuthenticationProvider Contracts

How Spring Security represents an in-flight or completed authentication request via the Authentication interface, and how AuthenticationProvider's authenticate()/supports() pair lets multiple authentication schemes coexist behind one AuthenticationManager.

80
Spring Security

Spring Security Crypto Module: Key Generators and Encryptors

How KeyGenerators produces salt/key values (StringKeyGenerator, BytesKeyGenerator) and how Encryptors builds encryption/decryption objects (standard AES/CBC, stronger AES/GCM, queryableText for searchable ciphertext) without pulling in a separate crypto library.

83
Spring Security🔬 Lab

Spring Security PasswordEncoder Contract and Encoding Strategies

How PasswordEncoder's encode()/matches() contract validates passwords without ever reversing a hash, how DelegatingPasswordEncoder lets an app support multiple algorithms at once via a prefix scheme, and why Argon2 is now a more prominent recommendation than the book's bcrypt/scrypt/PBKDF2 trio.

86
Spring Security

Spring Security JDBC and LDAP User Management

How JdbcUserDetailsManager manages users in a relational database via plain JDBC (default schema, overridable queries) and how LdapUserDetailsManager authenticates against an LDAP directory, both implementing the UserDetailsManager contract.

89
Spring Security🔬 Lab

Spring Security User Management

How UserDetails, GrantedAuthority, UserDetailsService, and UserDetailsManager describe and manage users in Spring Security, and why decorating a JPA entity with a separate UserDetails wrapper keeps persistence and security concerns apart.

92
Spring Security

Spring Security Authentication Architecture

How the authentication filter, AuthenticationManager, AuthenticationProvider, UserDetailsService, and SecurityContextHolder fit together, and how to configure them today with SecurityFilterChain instead of the deprecated WebSecurityConfigurerAdapter.

Spring Batch

21
Spring Batch

Integration and Functional Testing of Spring Batch Jobs

How the Spring-context-backed testing tiers work — the Spring TestContext Framework (@SpringJUnitConfig, context caching, @DirtiesContext) plus an embedded H2 datasource for integration tests that catch wiring bugs unit tests can't, StepScopeTestExecutionListener and its getStepExecution factory method (or StepScopeTestUtils.doInStepScope) to exercise @StepScope beans and late-bound SpEL outside a running step with MetaDataInstanceFactory-built domain objects, and functional tests that launch one real step or a whole job and assert on JobExecution/BatchStatus/StepExecution counts/table rows — plus the migration from the book's @RunWith(SpringJUnit4ClassRunner.class) to the all-in-one @SpringBatchTest, from the now-deprecated JobLauncherTestUtils.launchJob/launchStep to JobOperatorTestUtils.startJob/startStep, and away from the removed AssertFile helper.

22
Spring Batch

Unit Testing Batch Components with JUnit and Mockito

Batch jobs run headless with no UI to reveal a silent failure, so testing matters more than usual; this covers the white-box unit layer with zero Spring context — plain JUnit fixtures for a POJO Validator or ItemProcessor, Mockito mock/when/thenReturn/verify/times/never/verifyNoMoreInteractions to replace a FieldSet, JdbcTemplate, or reject-file writer and drive branches without a database or file system, spies plus RETURNS_DEEP_STUBS for a JobParametersValidator, and MetaDataInstanceFactory from spring-batch-test to build StepExecution/JobExecution/ExecutionContext fixtures (plus a hand-built StepContribution and ChunkContext) so a JobExecutionDecider, StepExecutionListener, or Tasklet is testable without launching a job; the 2012 book's JUnit 4 style (@RunWith(MockitoJUnitRunner), @Before/@After, @Test(expected=...)) maps to Jupiter (@ExtendWith(MockitoExtension.class), @BeforeEach/@AfterEach, assertThrows) since Spring Batch 6.0 dropped JUnit 4 entirely, Mockito's core API is unchanged in 5.x apart from Java 11+, the inline mock maker, verifyZeroInteractions removal, and strict stubs, and the 6.0 reorg moved the domain objects (core.job / core.step / core.job.parameters / infrastructure.item) while ItemWriter.write now takes Chunk instead of List and JobParametersInvalidException became InvalidJobParametersException.

23
Spring Batch

Fine-Grained Scaling in Spring Batch: Partitioning a Step

How a manager step splits input data into partitions that each run as their own StepExecution of an untouched worker step, the partitioning SPI (Partitioner returning a Map of named ExecutionContexts, StepExecutionSplitter, and a PartitionHandler that decides local threads via TaskExecutorPartitionHandler or remote workers via MessageChannelPartitionHandler), how gridSize and #{stepExecutionContext[...]} late binding feed per-partition parameters, why restart works without durable messaging, and how partitioning compares to multithreaded steps, parallel steps, and remote chunking — plus the Spring Batch 6.0 changes: manager/worker vocabulary, partition classes relocated to org.springframework.batch.core.partition, JobExplorer folded into JobRepository, XML replaced by PartitionStepBuilder, and two new strategies (local chunking, remote step).

24
Spring Batch

Remote Chunking: Scaling a Step Across Machines

Remote chunking distributes one chunk-oriented step across JVMs — a master keeps the ItemReader, JobRepository and step, dispatching ChunkRequests over durable, guaranteed-delivery middleware (JMS/AMQP) to slaves that process and write and return only a StepContribution summary — so it pays off only when reading isn't the bottleneck, and unlike partitioning it depends on transacted re-delivery rather than per-chunk batch metadata for correctness; the book's hand-wired Spring Integration channels, MessagingTemplate gateway, RemoteChunkHandlerFactoryBean and ChunkProcessorChunkHandler (shipped separately with Spring Batch Admin) are today the spring-batch-integration module's @EnableBatchIntegration plus RemoteChunkingManagerStepBuilder/RemoteChunkingWorkerBuilder in manager/worker terminology, with ChunkHandler renamed ChunkRequestHandler, ChunkProvider deprecated in 6.0 with no replacement, ChunkProcessor's arguments reordered, and two new 6.0 siblings — local chunking via ChunkTaskExecutorItemWriter and remote step execution via RemoteStep.

25
Spring Batch

Scaling Spring Batch Locally: Multithreaded Steps and Parallel Flows

How to scale a Spring Batch step on a single machine with a TaskExecutor-backed multithreaded step or independent parallel flows joined by a split, the thread-safety-vs-restartability tension this creates for stateful readers (saveState=false, a synchronized reader, or the process-indicator pattern), and the Spring Batch 6.0 redesign where only the ItemProcessor runs on multiple threads, plus virtual-thread executors for I/O-bound work.

26
Spring Batch

Monitoring Spring Batch Jobs: JobExplorer, JobOperator, and Metadata Schema

How to detect and act on job failures by reading execution history back from the job repository — the read-only JobExplorer for rich domain objects, the String/Long-typed JobOperator built for JMX, querying the BATCH_* metadata tables directly, and pushing alerts from a JobExecutionListener — plus the shift from hand-rolled JMX and the now-discontinued Spring Batch Admin to built-in Micrometer metrics and Spring Cloud Data Flow.

27
Spring Batch

Sharing Data Between Steps and Externalizing Flows in Spring Batch

How to pass a value from one step to a later one in a restart-safe way via the persisted job ExecutionContext and ExecutionContextPromotionListener versus a simpler but restart-unsafe holder bean, how to externalize a reusable sequence of steps as a Flow/FlowStep/JobStep, and how to end/fail/stopAndRestart a job declaratively from a step's exit status.

28
Spring Batch

Controlling Job Flow in Spring Batch: BatchStatus vs. ExitStatus

How Spring Batch branches a job's flow on a step's String ExitStatus (not the persisted BatchStatus enum) using on() with */? wildcards, how to mint a custom exit status from a StepExecutionListener.afterStep() or a JobExecutionDecider, and the flow terminators end/fail/stopAndRestart — plus the migration from the deprecated XML batch namespace to the Java FlowBuilder DSL.

29
Spring Batch

Spring Batch Transaction Management Patterns

How Spring Batch keeps a step atomic across two transactional resources such as a JMS queue and a database, using global XA/JTA transactions, the shared-resource pattern, best-effort 1PC, and duplicate handling through deduplication or idempotency.

30
Spring Batch

Spring Batch Transaction Management and Configuration

How Spring Batch drives transactions at the step level — one transaction per chunk (commit-interval) or per Tasklet.execute() — how to override isolation, propagation, and timeout with transaction attributes, the pitfalls of declarative transactions and transactional (JMS) readers, and how the unchanged PlatformTransactionManager model maps to today's .transactionManager()/.transactionAttribute() builder methods, jakarta.transaction, and the relocated ResourcelessTransactionManager.

31
Spring Batch

Spring Batch Restart and Recovery: Resuming Failed Jobs Where They Left Off

How Spring Batch restarts a FAILED or STOPPED job by launching a new JobExecution of the same JobInstance that resumes from state persisted in the ExecutionContext — enabling or forbidding restart with preventRestart, re-running completed steps with allowStartIfComplete, capping attempts with startLimit, and resuming mid-chunk through an ItemStream reader — all requiring a persistent JDBC JobRepository, plus the Spring Batch 6.0 shift to JobOperator.restart(JobExecution) and the new recover() operation.

32
Spring Batch

Spring Batch Retrying on Error: RetryPolicy, RetryTemplate, and AOP Retry

How Spring Batch re-attempts transient failures instead of skipping or failing them — RetryPolicy objects with back-off, RetryListener hooks, the standalone RetryTemplate for arbitrary code, and transparent AOP retry — plus the retry API's journey from Spring Batch's own package to the Spring Retry library and, in Spring Batch 6.0, to Spring Framework 7's native core retry.

33
Spring Batch

Spring Batch Skipping Instead of Failing: SkipPolicy and SkipListener

How Spring Batch skips faulty items instead of failing the step — read/process/write skip semantics, custom SkipPolicy implementations, and SkipListener callbacks for recording or dead-lettering skipped records.

34
Spring Batch

Spring Batch Filtering and Validating Items

How a Spring Batch ItemProcessor filters items by returning null (a filter, not a skip), validates them with ValidatingItemProcessor and the built-in BeanValidatingItemProcessor, and chains rules with CompositeItemProcessor.

35
Spring Batch

Item Processing and Transformation: The ItemProcessor Contract

How an ItemProcessor sits between the reader and writer in a chunk-oriented step to transform items in place, change the read type into a different write type, or hydrate a driving query — plus PassThroughItemProcessor and ItemProcessorAdapter.

36
Spring Batch

Advanced and Composite Item Writers in Spring Batch

How Spring Batch reuses an existing service as a writer with ItemWriterAdapter, implements a custom ItemWriter through the write(Chunk) contract, and fans out or routes a chunk with CompositeItemWriter versus ClassifierCompositeItemWriter — plus the niche JMS and email writers — and how those classes moved to the org.springframework.batch.infrastructure.item.* packages in Spring Batch 6.0.

37
Spring Batch

Spring Batch Database Item Writers

How Spring Batch writes a chunk to a relational database — JdbcBatchItemWriter collapsing N inserts into a single JDBC batch per chunk, the named- versus positional-parameter binding strategies, and the JpaItemWriter/HibernateItemWriter ORM writers, plus the Spring Batch 6.0 builder APIs and the infrastructure.item package relocation.

38
Spring Batch

Writing Files in Spring Batch

How Spring Batch's chunk-oriented ItemWriter contract and the FlatFileItemWriter, StaxEventItemWriter, and MultiResourceItemWriter turn domain objects into delimited, fixed-width, XML, and rolling file-set output, plus the modern builder equivalents and 6.0 package relocation of the book's XML configuration.

39
Spring Batch

Custom and Service ItemReaders in Spring Batch

How Spring Batch plugs non-standard input into a chunk step—reusing an existing bean method with ItemReaderAdapter, draining a queue with JmsItemReader, and hand-writing a custom ItemReader made restartable via ItemStream—and how those classes moved to the org.springframework.batch.infrastructure.item.* packages in Spring Batch 6.0.

40
Spring Batch

Reading from Relational Databases: JDBC and ORM Item Readers

How Spring Batch streams rows from relational databases with cursor-based and paging item readers over JDBC and ORM, and how today's builder APIs and relocated packages differ from the book's XML configuration.

41
Spring Batch

Reading XML and Multiple Resources in Spring Batch

Stream large XML input one fragment at a time with StaxEventItemReader and a Spring OXM unmarshaller, and process an ordered set of files as one continuous item stream with MultiResourceItemReader.

42
Spring Batch

Reading Flat Files in Spring Batch

How Spring Batch's ItemReader contract and FlatFileItemReader turn delimited, fixed-width, multiline, heterogeneous, and JSON file records into domain objects, and the modern builder and JsonItemReader equivalents of the book's XML configuration.

43
Spring Batch

Stopping Spring Batch Jobs Gracefully

How to stop a Spring Batch job cleanly — from the outside as an operator with JobOperator.stop and from inside a step as a developer with StepExecution.setTerminateOnly — so the job halts at the next chunk boundary within transactional safety and ends in a restartable STOPPED state, and how those APIs shifted in Spring Batch 6.0 where JobOperator (extending JobLauncher) is the API and the book's stop(long)/getRunningExecutions calls are deprecated for removal.

44
Spring Batch

Launching Spring Batch Jobs from a Web Application

How embedding Spring Batch in a web application's Spring context keeps a resident batch environment warm—avoiding a fresh JVM per job—and how a Spring MVC controller launches jobs on demand over HTTP asynchronously, a hand-wired setup that Spring Boot now auto-configures with JobOperator replacing the deprecated JobLauncher.

58
Spring Batch

Triggering Spring Batch Jobs: cron vs. the Spring Scheduler

How cron's crontab entries trigger CommandLineJobRunner as a fresh OS process on a schedule, how Spring's @Scheduled/TaskScheduler support offers an in-process alternative with fixedRate/fixedDelay/cron options since Spring 3.0, and why Kubernetes CronJob has largely replaced raw crontab as the deployment model for the same trigger-a-batch-process pattern.

62
Spring Batch

Launching Spring Batch Jobs from the Command Line

How CommandLineJobRunner launches a job as a plain java -classpath process for cron-style scheduling — Spring config file, job name, typed job parameters, and an ExitCodeMapper that turns a job's exit status back into a shell exit code — and why it's deprecated since Spring Batch 6.0 in favor of the operation-aware CommandLineJobOperator.

64
Spring Batch

The Spring Batch Launcher API: Synchronous vs. Asynchronous Job Launches

How the JobLauncher interface's single run(Job, JobParameters) method starts a job execution, why the default launch is synchronous and blocks the calling thread until the job finishes, how supplying a TaskExecutor makes it asynchronous instead, and how JobLauncher/SimpleJobLauncher/TaskExecutorJobLauncher have all been deprecated since Spring Batch 6.0 in favor of JobOperator/TaskExecutorJobOperator.

67
Spring Batch

Spring Batch XML Configuration Inheritance: abstract and parent

How Spring Batch's XML vocabulary reuses plain Spring's abstract/parent bean-inheritance mechanism to let a job or step definition inherit and override another's attributes, how the merge="true" flag combines rather than replaces a parent's listener list, and why Java configuration has no direct equivalent — reuse there is achieved by extracting shared configuration into ordinary Java methods instead of a dedicated inheritance keyword.

70
Spring Batch

Spring Batch Listeners: Hooking Into Job, Step, and Item Lifecycle Events

How JobExecutionListener/StepExecutionListener/ChunkListener and the per-item ItemReadListener/ItemProcessListener/ItemWriteListener/SkipListener interfaces let you plug notification and error-handling logic into a batch job's lifecycle without touching the job's own reader/processor/writer code, and how @BeforeStep/@AfterStep-style annotations offer the same hooks on a plain POJO instead of an interface implementation.

73
Spring Batch

Spring Batch Step Scope and SpEL Late Binding

How Spring Batch's custom StepScope bean scope delays bean instantiation until a step actually starts, and how SpEL expressions against jobParameters/jobExecutionContext/stepExecutionContext let a reader, writer, or tasklet pull in a value — like an input filename — that's only known at launch time instead of being hardcoded in configuration.

76
Spring Batch

Spring Batch Job Repository: Choosing and Configuring the Persistence Layer

How the book's <batch:job-repository> XML attributes (data-source, transaction-manager, isolation-level-for-create, table-prefix, max-varchar-length, lob-handler) configure the one JobRepository implementation Spring Batch ships, SimpleJobRepository, and how the same attributes map onto today's @EnableJdbcJobRepository — including why isolation-level-for-create defaults to SERIALIZABLE as a safeguard against launching the same job instance twice from different nodes.

79
Spring Batch

Spring Batch Fault-Tolerant Steps: Skip, Retry, and Transaction Attributes

How the book's chunk/tasklet XML attributes (skip-limit, retry-policy, cache-capacity, transaction-attributes, no-rollback-exception-classes) map onto Java configuration — first onto the now-deprecated FaultTolerantStepBuilder, and, as of Spring Batch 6.0, onto ChunkOrientedStepBuilder's policy-object-based retryPolicy()/skipPolicy() built on Spring Framework's own core retry feature instead of the Spring Retry library.

82
Spring Batch

Spring Batch Job Configuration: Restart, Incrementer, and Validator

How the book's XML job/step attributes (restartable, incrementer, validator, next, parent/abstract) map onto JobBuilder's preventRestart()/incrementer()/validator()/next() methods, and why Java configuration doesn't need an equivalent to XML's parent/abstract inheritance.

85
Spring Batch

Spring Batch Non-Linear Flow and Job Instance Identity

How a JobExecutionDecider routes a job's flow based on a step's outcome, how JobInstance identity is derived from a job plus its identifying JobParameters, and why JobLauncher is deprecated in Spring Batch 6.0 in favor of JobOperator.

88
Spring Batch

Spring Batch Job Repository, Launcher, and Job Model

How the JobLauncher and JobRepository infrastructure components work, why persistent vs. in-memory job repositories trade off monitoring and restart against overhead, and how a job is modeled as a sequence of steps with optional non-linear control flow. Note: JobLauncher is now deprecated in favor of JobOperator as of Spring Batch 6.0.

91
Spring Batch

Spring Batch Chunk-Oriented Processing

How Spring Batch's Job/Step/JobInstance/JobExecution/StepExecution model and chunk-oriented ItemReader/ItemProcessor/ItemWriter processing work, and how Java-based JobBuilder/StepBuilder configuration replaced the now-deprecated XML namespace.