Spring Framework
Spring is how most backend Java gets written, from the IoC container at the bottom to Boot, MVC, WebFlux, Data, Security and Cloud on top. Almost every JVM backend interview lives somewhere in this tree, and the questions test whether you know what the framework is doing underneath the annotations.
on this pageshowhide
guide
overview
~2 minSpring is the most common way backend Java — and a large share of backend Kotlin — gets written, so a JVM backend interview usually turns into a Spring conversation somewhere. The annotations make it easy to write working code without knowing what runs it, and interviewers probe exactly that gap. They ask what the container does before your first line executes, why an annotation silently had no effect, what a transaction boundary really covers, and which default Boot chose on your behalf. A good answer names the mechanism underneath — the bean definition, the proxy, the condition, the filter — not only the annotation on top. The hub follows the stack from the bottom up. [Core container and IoC](/topics/be-spring-core) is the foundation: beans, injection, scopes, lifecycle and the Environment. [Aspect-oriented programming](/topics/be-spring-aop) explains the proxies most other features lean on, and [transaction management](/topics/be-spring-tx) is the most common job those proxies do. [Spring Boot](/topics/be-spring-boot) is the opinionated layer that configures all of it from the classpath and properties. The web tier comes as two stacks, the servlet-based [Spring MVC](/topics/be-spring-mvc) and the reactive [Spring WebFlux](/topics/be-spring-webflux). [Spring Data](/topics/be-spring-data) and [Spring Security](/topics/be-spring-security) cover persistence and protection; [testing](/topics/be-spring-testing) and [observability and Actuator](/topics/be-spring-observability) cover proving a service works and watching it run. Beyond a single service sit [Spring Cloud](/topics/be-spring-cloud), [messaging and integration](/topics/be-spring-messaging) and [Spring Batch](/topics/be-spring-batch). [AOT and native image](/topics/be-spring-aot-native) moves startup work into the build, and the [wider portfolio](/topics/be-spring-ecosystem) collects GraphQL, Modulith, Spring AI and the smaller projects. Junior rounds check vocabulary: what a bean is, how injection picks a candidate, what a starter or a profile does, how a controller maps a request. Middle rounds move to behaviour people learn by getting it wrong — a transaction that did not roll back, a lazy association read after its session closed, a test suite that rebuilds its context for every class. Senior and principal rounds turn into design and diagnosis: MVC or WebFlux, where the transaction boundary belongs, how to keep a large suite fast, what native compilation costs, and how to read a struggling service from its health checks and metrics. Learn the container first, then proxies; most "why doesn't this annotation work" questions come down to one of the two. Boot, the web tier, transactions and data follow from there, and every other section builds on those.
primer
### The container builds the object graph Spring's core is an **inversion-of-control container**: your classes declare what they need, and the `ApplicationContext` decides how to create, wire and eventually destroy them. It works in two phases. First it collects **bean definitions** — from component scanning, `@Bean` methods and auto-configuration — and lets infrastructure inspect or rewrite them; only then does it create instances. Many startup failures, ordering puzzles and "why is this property null" questions are really questions about which phase something runs in. ### Wiring is resolved by type, at startup The container matches each dependency against the beans it holds, by type first, then by qualifier, name or a primary marker when several candidates fit. Because a standard context creates its non-lazy singletons during startup, a missing or ambiguous candidate usually stops the application at boot rather than on the first request. Constructor injection is the style most teams now defend: dependencies are visible in the signature, fields can be final, and the class can be built in a plain unit test. ### Annotations are metadata; proxies do the work `@Transactional`, `@Cacheable`, `@Async`, `@PreAuthorize` and your own aspects change nothing by themselves. Infrastructure notices them and hands callers a **proxy** that runs extra behaviour around matching method calls. Most "the annotation was ignored" stories follow from that: a call from inside the same object, a method the proxy cannot intercept, a bean used before its proxy exists. Know the proxy and you can predict the failure. ### Boot is conditional configuration Spring Boot does not replace the framework. It registers configuration classes guarded by **conditions** — a class present on the classpath, a property set, no bean of that type defined yet. Starters bring the libraries, auto-configuration reacts to them, and externalized configuration tunes the result through a fixed precedence order. The habit interviewers look for: when you declare your own bean, most auto-configuration steps aside, and you can explain why from the condition rather than from memory. ### Bugs gather at boundaries A transaction, a security context, a persistence session and a request thread each have an edge, and defects cluster there: an exception swallowed before it reaches the transaction proxy, lazy data touched after the session closed, work handed to another thread that no longer sees the caller's identity. Strong answers say where the boundary sits and what crosses it. ### Two web stacks, one programming model Spring MVC runs on the Servlet API with a thread held per request; WebFlux runs on a few non-blocking event-loop threads over Project Reactor. The controller annotations look nearly identical, which hides how different the runtimes are. Choosing between them is a trade-off conversation — blocking dependencies, streaming needs, team experience and, on recent Java, virtual threads — not a question of which one is faster. ### Security runs in front, as filters On the servlet stack, Spring Security is a chain of filters that sees each request before the `DispatcherServlet` does, plus method-level checks built on the same proxies as everything else. Authentication establishes who the caller is and stores it in a context; authorization reads that context. Most security questions test whether you can say which filter or which check made a given decision. ### Startup cost is moving to build time Reflection, classpath scanning and condition evaluation make a Spring context flexible and slow to start. **AOT processing** does much of that work during the build and emits generated code, which is what makes a GraalVM native image possible — at the price of a closed world in which anything dynamic has to be declared in advance. ### Tests are priced by context size A test that loads the full application is realistic and slow; a slice loads one layer; a plain unit test loads nothing. The TestContext framework reuses a context across test classes that share the same configuration, so per-class mock sets and dirty-context markers are often what makes a suite slow — a senior question dressed as a testing one.
- Bean
- An object whose creation, wiring and lifecycle are managed by the Spring container rather than by the code that uses it.
- ApplicationContext
- The main container interface of a Spring application. It holds bean definitions and beans, and adds events, resource loading, messages and the Environment on top of plain bean creation.
- Bean definition
- The recipe for a bean — class, scope, dependencies, init and destroy callbacks — registered before any instance exists and open to changes by infrastructure.
- BeanPostProcessor
- A container extension called for every bean around initialization. It may modify or replace the instance, which is how Spring substitutes proxies for annotated beans.
- Component scanning
- Discovery of classes carrying stereotype annotations such as @Component or @Service in chosen packages, each registered as a bean definition.
- Bean scope
- How many instances the container creates and for how long: one per container for singleton, one per lookup for prototype, one per HTTP request or session on the web.
- Qualifier
- A marker that narrows injection to one of several beans of the same type, by bean name or by a custom annotation.
- Proxy
- A generated object standing in for a bean that intercepts method calls to add behaviour; built from the bean's interfaces (JDK proxy) or as a subclass (CGLIB).
- Advice and pointcut
- Advice is the code an aspect runs before, after or around a method call; a pointcut is the expression deciding which calls it applies to.
- Auto-configuration
- Boot's conditional configuration classes, applied according to the classpath and properties, which back off when the application defines the same beans itself.
- Starter
- A single dependency that brings a tested, version-aligned set of libraries for one capability, which in turn triggers the matching auto-configuration.
- Environment
- The container's view of configuration: property sources ordered by precedence, plus the active profiles. Placeholders and configuration properties resolve against it.
- Profile
- A named switch that activates groups of beans and configuration files only in the environments where it is turned on.
- DispatcherServlet
- Spring MVC's front controller. It receives each request, locates the handler, invokes it, and turns the result or exception into an HTTP response.
- SecurityFilterChain
- A configured list of Spring Security filters applied to requests matching a pattern; the servlet-side entry point for authentication, authorization and exploit protection.
- Transaction propagation
- The rule for what a transactional method does when called with or without an existing transaction: join it, suspend it, start a new one, or refuse.
- Repository
- In Spring Data, an interface declaring persistence operations for one entity type; the framework supplies the implementation at runtime.
- Test slice
- A Boot test annotation that builds a context for one layer, such as web or JPA, leaving other layers out or replaced by mocks.
- Context cache
- The TestContext framework's reuse of an application context across test classes with identical configuration, so each class does not rebuild it.
- Actuator
- Boot's production module exposing health, metrics, info and diagnostic endpoints over HTTP or JMX.
- AOT processing
- Build-time analysis of the application context that generates code and hints in place of runtime reflection and scanning; the basis for GraalVM native images.
### Startup Follow a Spring Boot service from launch to its first request. `SpringApplication` first assembles the Environment — property files, profiles, environment variables, command-line arguments — and then creates the application context. Component scanning and auto-configuration register bean definitions, and conditions decide which auto-configured ones survive. Post-processors then create the beans and put proxies in front of those carrying transactional, caching, async or security annotations. Once the context is refreshed, Boot starts the embedded server, and Actuator's health and readiness state tell the platform the instance can take traffic. ### A request On the servlet stack the embedded server passes each request through the security filter chain, which authenticates the caller and applies URL rules. The `DispatcherServlet` then picks a handler, converts and validates the body, and invokes the controller. The controller calls a service through its proxy, which opens the transaction; the service calls a Spring Data repository — itself a generated proxy — which runs queries on a pooled connection bound to that transaction. On the way out, exceptions are mapped to responses, and Micrometer records timings and trace spans around the whole exchange. WebFlux follows the same outline with a reactive filter chain, a `DispatcherHandler` and non-blocking I/O. Several of those layers meet in one ordinary class: ```java @Service public class OrderService { private final OrderRepository orders; // interface only; Spring Data supplies it private final ApplicationEventPublisher events; // a container service, injected like any bean public OrderService(OrderRepository orders, ApplicationEventPublisher events) { this.orders = orders; this.events = events; } @Transactional // honoured only when the call arrives through the proxy public Order place(OrderRequest request) { Order saved = orders.save(Order.from(request)); events.publishEvent(new OrderPlaced(saved.getId())); return saved; } } ``` Nothing in the class opens a transaction or looks up a collaborator. The container supplied both constructor arguments, `orders` is backed by an implementation nobody wrote, and the annotation takes effect only because callers hold a proxy rather than the object itself — call `place` from another method of the same class and no transaction starts. A listener bound to a transaction phase can hold the event's side effects until after commit. ### Beyond one service The remaining sections attach to the same skeleton. Spring Cloud and the messaging projects stretch it across process boundaries: configuration fetched from a server, remote calls through declarative clients, work handed to brokers through listener containers. Spring Batch runs chunked jobs as beans in the same container and keeps its run history in a database. Test slices and the TestContext framework build reduced copies of this context, and AOT processing computes it ahead of time for a native image.
- Core Container & IoC →
Beans, injection, scopes and lifecycle: the container every other section assumes you can already explain.
- Aspect-Oriented Programming →
Proxies and advice are the mechanism behind transactions, caching, async and method security; learn them before those features.
- Spring Boot →
How auto-configuration, starters and externalized configuration assemble the container you work with every day.
- Spring MVC (Servlet Web) →
The servlet web stack most Spring services are built on, from request mapping to error handling.
- Transaction Management →
Transaction boundaries, propagation and rollback rules — where data-integrity questions land and proxy knowledge pays off.
- Spring Data →
The repository model and its JPA integration, easiest to follow once transactions are clear.
Explaining
@Transactionalor@Cacheableas if the annotation acts on its own; without the proxy you cannot explain self-invocation — see Proxy Limitations & Aspect Ordering.Assuming any exception rolls back a transaction: the default rules treat checked and unchecked exceptions differently, and an exception your code catches before it reaches the transaction proxy triggers no rollback.
Describing Spring Boot as a separate framework; it configures Spring Framework, and each Boot behaviour traces back to a condition, a property or a bean you can override.
Choosing WebFlux because it is "faster", then calling blocking JDBC or HTTP clients on event-loop threads, which stalls every request those threads serve.
Using
@SpringBootTestfor every test and varying mocks from class to class, so the context cache misses and the suite rebuilds the application repeatedly.Leaning on open-session-in-view to hide
LazyInitializationExceptioninstead of loading what the response needs inside the transaction — see Proxy Pitfalls & Rollback Semantics.Injecting a prototype bean into a singleton and expecting a fresh instance per use; it is created once, at injection, unless you look it up through a provider.
Exposing every Actuator endpoint over HTTP with a wildcard and no security rule; some reveal configuration values, others change runtime settings such as log levels.
Quoting pre-Security-6 configuration —
WebSecurityConfigurerAdapter,antMatchers— as current; name the version you describe, or use the component-basedSecurityFilterChainstyle.
This guide assumes Spring Framework 6.x with Spring Boot 3.x, the line most production code and most questions below describe. Spring Framework 7 and Spring Boot 4, released in late 2025, keep the programming model; when an answer depends on the newer line, say so. The changes interviewers still ask about: - **Framework 6.0 / Boot 3.0** raised the baseline to Java 17 and moved the Servlet, JPA and validation APIs from the `javax.*` to the `jakarta.*` namespace, which is why migration questions start with imports. AOT processing and GraalVM native image support became part of the core portfolio, and tracing moved from Spring Cloud Sleuth to Micrometer's Observation API. - **Boot 3.0** stopped reading auto-configuration classes from `spring.factories`; they are listed in `META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`, so older custom starters need that change. - **Spring Security 6.0** removed `WebSecurityConfigurerAdapter` in favour of `SecurityFilterChain` beans, `authorizeHttpRequests` superseded `authorizeRequests`, and `requestMatchers` replaced the `antMatchers`-style methods. - **Spring Batch 5** replaced the builder factories with builders that take the job repository directly. - **Framework 6.1 / Boot 3.2** added `RestClient`, a fluent synchronous client alongside `RestTemplate`, and support for running request handling on virtual threads. - **Framework 6.2 / Boot 3.4** introduced `@MockitoBean` and `@MockitoSpyBean` in the Framework's test support, and Boot's `@MockBean` and `@SpyBean` were deprecated in their favour. A candidate who can place a snippet in its era — `javax` imports, an adapter subclass, a builder factory — reads older codebases quickly and avoids presenting retired APIs as current.
Interviewers expect you to place Spring among JVM backend options, not only to use it. The oldest comparison is **Jakarta EE**: Spring consumes many Jakarta specifications — Servlet, JPA, Bean Validation — but brings its own container, configuration model and release cadence instead of following an application-server standard. The newer comparison is with **Quarkus** and **Micronaut**, which were built to resolve dependency injection and configuration largely at build time; they start faster and use less memory by default, while Spring offers the larger ecosystem and more runtime flexibility, and narrows the gap with AOT and native images. Lighter options such as **Ktor**, from JetBrains, or **Javalin** trade Spring's breadth for a smaller, more explicit core. Inside the Spring world the projects themselves are the ecosystem: Boot assembles them, and Data, Security, Cloud and Batch all plug into the same container. Kotlin is a first-class language with its own extensions and coroutine support. Around the application sit the libraries answers keep naming — Hibernate as the usual JPA provider, Jackson for JSON, Micrometer for metrics, Resilience4j for circuit breaking, Testcontainers for integration tests. A defensible framework choice names the workload: a large team with many integrations favours Spring's breadth, while scale-to-zero functions weigh startup and footprint first.
explore
- Core Container & IoC224 questions
- Container & Bean Definitions26 questions
- Configuration & Component Model36 questions
- Dependency Injection29 questions
- Scopes & Bean Lifecycle45 questions
- Environment, Properties & SpEL20 questions
- Container Services32 questions
- Scheduling, Async & Caching36 questions
- Aspect-Oriented Programming152 questions
- AOP Model & the @AspectJ Style29 questions
- Pointcut Designators29 questions
- Advice Types & Join Points29 questions
- Proxy Mechanics: JDK vs CGLIB27 questions
- Proxy Limitations & Aspect Ordering19 questions
- AspectJ Weaving & Framework Integrations19 questions
- Transaction Management150 questions
- Transaction Manager Abstraction29 questions
- Declarative @Transactional25 questions
- Propagation Behaviors23 questions
- Programmatic Transactions20 questions
- Proxy Pitfalls & Rollback Semantics33 questions
- Synchronization & Transactional Events20 questions
- Spring MVC (Servlet Web)171 questions
- Request-Processing Lifecycle25 questions
- Controllers, Mapping & Handler Methods36 questions
- Message Conversion & Content Negotiation20 questions
- Exception Handling & Validation25 questions
- Interceptors, CORS, Multipart & Async25 questions
- Synchronous HTTP Clients20 questions
- MVC Configuration & Infrastructure20 questions
- Spring WebFlux (Reactive Web)145 questions
- Reactive Streams & Project Reactor30 questions
- Non-Blocking Runtime & Threading Model20 questions
- Annotated & Functional Endpoints30 questions
- Reactive WebClient19 questions
- Filters, Codecs, Errors & Streaming31 questions
- Reactive Context & Choosing WebFlux15 questions
- Spring Boot155 questions
- Auto-Configuration25 questions
- Starters & Dependency Management20 questions
- Externalized Configuration & Profiles35 questions
- SpringApplication & Lifecycle24 questions
- Embedded Servers21 questions
- Packaging, Build Plugins & DevTools30 questions
- Spring Data156 questions
- Repository Programming Model (Commons)30 questions
- Paging, Sorting, Projections & Auditing24 questions
- Spring Data JPA35 questions
- Spring Data JDBC & R2DBC25 questions
- Spring Data MongoDB & Redis31 questions
- Spring Data REST11 questions
- Spring Security186 questions
- Filter Chain Architecture30 questions
- Authentication35 questions
- HTTP Authorization18 questions
- Method Security24 questions
- OAuth2, OIDC & Resource Server30 questions
- Web Exploit & Session Protections30 questions
- Reactive Security & Testing19 questions
- Spring Cloud144 questions
- Externalized Configuration36 questions
- Service Discovery & Load Balancing25 questions
- Spring Cloud Gateway30 questions
- Declarative Clients & Resilience23 questions
- Messaging with Spring Cloud Stream15 questions
- Tracing, Contracts & Functions15 questions
- Messaging & Integration141 questions
- Spring Messaging Abstraction15 questions
- Spring Integration (EIP)25 questions
- JMS Support20 questions
- Spring AMQP / RabbitMQ25 questions
- Spring for Apache Kafka31 questions
- WebSocket & STOMP Messaging15 questions
- RSocket Messaging10 questions
- Spring Batch148 questions
- Batch Domain Model25 questions
- Step Processing & Item Flow34 questions
- Launching, Parameters & Metadata34 questions
- Fault Tolerance20 questions
- Scaling & Parallel Processing20 questions
- Flow Control15 questions
- Testing171 questions
- Spring TestContext Framework25 questions
- @SpringBootTest & Full Context26 questions
- Test Slices29 questions
- Endpoint Testing & Assertions40 questions
- Mocking Collaborators & Test Fixtures20 questions
- Persistence & Integration Testing31 questions
- Observability & Actuator148 questions
- Actuator Endpoints & Exposure42 questions
- Health Indicators & Probes26 questions
- Micrometer Metrics & Export35 questions
- Observation API & Distributed Tracing25 questions
- Application Logging20 questions
- AOT & Native Image145 questions
- Spring AOT Engine25 questions
- GraalVM Native Image Fundamentals23 questions
- Reachability Metadata & RuntimeHints31 questions
- Native Build Tooling24 questions
- AOT & Native Testing18 questions
- Startup, Footprint & JVM Alternatives24 questions
- Wider Spring Portfolio144 questions
- Spring GraphQL (has its own guide)34 questions
- Spring HATEOAS14 questions
- Spring Web Services (SOAP)14 questions
- Spring Modulith21 questions
- Spring AI36 questions
- Session, Shell & Other Portfolio Projects25 questions
→ has its own guide
questions
2,380 · 15 sectionsWhat does @ComponentScan do, and how do you tell it which packages to scan?
basics
~10 s@ComponentScan tells Spring to search packages for classes annotated with @Component (and @Service, @Repository, @Controller) and register them as beans. You point it at packages with basePackages, e.g. @ComponentScan(basePackages = "com.app").
What is @Conditional and the Condition interface in Spring, and how do you use them to register a bean only under certain circumstances?
basics
~10 s@Conditional is an annotation you put on a @Bean or @Configuration. It points to a class implementing the Condition interface, whose matches() method returns true/false. Spring registers the bean only when matches() returns true.
What are @Configuration and @Bean, and how do you use them to define a Spring bean?
basics
~10 s@Configuration marks a class as a source of bean definitions. Inside it, a method annotated with @Bean returns an object that Spring registers as a bean in the application context, managing its lifecycle.
What is functional (programmatic) bean registration in Spring, and how does it differ from declaring beans with @Bean or @Component?
basics
~10 sIt registers beans by calling code — e.g. context.registerBean(MyService.class, MyService::new) — instead of using @Component scanning or @Bean methods. You give Spring a name, a type, and a lambda that creates the instance.
What is Spring's @Import annotation and what kinds of classes can you import with it?
basics
~10 s@Import lets one Java @Configuration class pull in beans defined in another. You can import other @Configuration classes, ImportSelector or ImportBeanDefinitionRegistrar implementations, and (since Spring 4.2) plain component classes.
What is @After advice in Spring AOP and when does it run?
basics
~20 s@After is advice that runs after a matched method finishes — whether it returned normally or threw an exception. It behaves like a finally block, so it is used for cleanup. It cannot see the return value or the exception.
What does Spring's @AfterReturning advice do, and when does it run?
basics
~10 s@AfterReturning is AOP advice that runs after an advised method finishes successfully (returns normally). It does NOT run if the method throws an exception. It can read the returned value but cannot replace it.
What is @AfterThrowing advice in Spring AOP and when does it run?
basics
~10 s@AfterThrowing is an aspect advice method that runs only when the matched method (join point) exits by throwing an exception. If the method returns normally, it does not run.
What is @Around advice in Spring AOP, and why must it call ProceedingJoinPoint.proceed()?
basics
~20 s@Around wraps a method call. It runs code before and after the target method. You must call proceed() to actually run the target method; if you skip it, the target never executes and you return your own value instead.
What is @Before advice in Spring AOP and when does it run?
basics
~10 s@Before advice is aspect code that runs before a matched method (the join point) executes. It's used for things like logging entry or validating arguments. It runs before, then the real method still runs.
What does @Transactional do, and what happens around a method annotated with it?
basics
~10 s@Transactional tells Spring to run the method inside a database transaction: Spring starts a transaction before the method, commits if it returns normally, and rolls back if it throws a runtime exception.
What does the `isolation` attribute of `@Transactional` control, and what are the five values Spring offers?
basics
~10 sIt sets how much one transaction is shielded from data other in-flight transactions are changing. Spring's Isolation enum offers DEFAULT, READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, and SERIALIZABLE — higher levels give more consistency but less concurrency.
What does @Transactional(readOnly = true) do in Spring?
basics
~20 sIt marks a transaction as read-only: a hint that the method only reads data. Spring passes this to Hibernate and the JDBC driver so they can optimize, for example by skipping dirty-checking and the automatic flush.
By default, which exceptions cause a Spring @Transactional method to roll back, and which let it commit?
basics
~10 sBy default Spring rolls back on unchecked exceptions (RuntimeException) and Error. It commits on checked exceptions (any Exception that isn't a RuntimeException). You must opt in to roll back on checked exceptions.
What does the timeout attribute of @Transactional do, and in what unit do you specify it?
basics
~10 s@Transactional(timeout = N) limits how long the transaction may run to N seconds. If it exceeds that, Spring aborts it and rolls back, throwing a TransactionTimedOutException. The unit is always seconds.
How do you add a Cache-Control response header to a Spring MVC controller method, and what does the CacheControl builder give you?
basics
~10 sReturn a ResponseEntity and call .cacheControl(...) with Spring's CacheControl builder, e.g. CacheControl.maxAge(Duration.ofMinutes(10)).cachePublic(). Spring writes the correct Cache-Control header (max-age=600, public) so browsers/proxies can cache the response.
How do you serve static files (CSS, JS, images) in Spring MVC, and where does Spring Boot look for them by default?
basics
~10 sPut files under src/main/resources/static (or public/resources/META-INF/resources) and Spring Boot serves them automatically at the URL root. To configure manually, override addResourceHandlers in a WebMvcConfigurer.
What is UriComponentsBuilder and why use it instead of string concatenation to build URLs?
basics
~20 sUriComponentsBuilder is a Spring helper that builds a URI piece by piece — scheme, host, path, query params — and handles proper encoding for you. It avoids bugs from manually gluing strings and forgetting to escape special characters.
What is WebMvcConfigurer and how do you use it to customize Spring MVC?
basics
~10 sWebMvcConfigurer is an interface with default (empty) callback methods. You create a @Configuration class implementing it and override only the callbacks you need, like addInterceptors or addViewControllers, to tweak MVC without replacing everything.
How does Spring MVC decide what value to pass to each parameter of a @RequestMapping controller method?
basics
~20 sFor every controller-method parameter Spring asks a list of HandlerMethodArgumentResolver strategies which one can handle it. The first that says yes resolves the value (from a request param, path variable, body, etc.) and passes it in.
What is the Reactor Context and why does reactive code need it instead of ThreadLocal?
basics
~10 sReactor Context is a small immutable key-value map carried along a reactive pipeline. It replaces ThreadLocal because reactive operators hop between threads, so ThreadLocal values would be lost.
In a Spring WebFlux controller, how do you obtain the currently authenticated user, and why can't you just call SecurityContextHolder.getContext()?
basics
~10 sUse ReactiveSecurityContextHolder.getContext(), which returns a Mono<SecurityContext> you map to the Authentication/principal. The blocking SecurityContextHolder reads a ThreadLocal, which isn't reliably set on WebFlux's shared event-loop threads.
What is the core difference between Spring MVC and Spring WebFlux, and when would you pick each?
basics
~20 sMVC is blocking and uses one thread per request; WebFlux is non-blocking and reactive, handling many concurrent requests on a few threads. Pick WebFlux for high concurrency with slow I/O; MVC for simpler, mostly CPU or blocking-DB work.
How do you write an annotated reactive controller in Spring WebFlux, and what changes compared to a Spring MVC controller?
basics
~10 sUse the same annotations as MVC (@RestController, @GetMapping, @PathVariable), but return reactive types: Mono<T> for zero-or-one value and Flux<T> for a stream of values, instead of a plain object.
How do you write a Spring WebFlux controller handler using Kotlin coroutines, and how do suspend functions and Flow<T> return types map onto the reactive model?
basics
~20 sMark the handler method suspend fun and return a plain value or a Flow<T> instead of Mono/Flux. Spring adapts a suspend function to a single-value response and a Flow to a streaming (many-value) response automatically.
What are @ConditionalOnClass and @ConditionalOnMissingClass, and why does Spring Boot auto-configuration rely on them?
basics
~10 s@ConditionalOnClass makes a bean/config load only if a named class is on the classpath; @ConditionalOnMissingClass only if it's absent. Boot uses them so auto-config activates just when the relevant library is present.
What is a custom auto-configuration in Spring Boot, and how do you register it so Spring Boot picks it up automatically?
basics
~10 sA configuration class annotated with @AutoConfiguration that defines @Bean methods. You register it by listing its full class name in the file META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports so Spring Boot loads it on startup.
What is @EnableAutoConfiguration and how does it end up on your application?
basics
~10 s@EnableAutoConfiguration tells Spring Boot to automatically configure beans based on what's on the classpath. You rarely write it directly because @SpringBootApplication already includes it.
What is @ConfigurationProperties and how does it differ from @Value?
basics
~10 s@ConfigurationProperties binds a whole group of external properties (from application.yml/properties/env) onto the fields of a POJO in a type-safe way. @Value injects a single property value into one field using a placeholder expression.
What does the `spring.config.import` property do, and what is the effect of the `optional:` prefix?
basics
~10 sspring.config.import tells Spring Boot to pull in extra config from another location (a file, config tree, etc.) during startup. optional: means: if that location is missing, don't fail — just skip it.
What is Query by Example (QBE) in Spring Data, and what are the three building blocks?
basics
~20 sQuery by Example lets you search by filling in a sample entity (a 'probe'). Spring turns the non-null fields into a WHERE clause. The three parts are: Probe (the sample entity), ExampleMatcher (matching rules), and Example (probe + matcher combined).
What is a custom fragment interface in Spring Data, and how does Spring find its implementation?
basics
~10 sA fragment is a small interface declaring custom repository methods you write yourself. Your repository extends it, and Spring finds the implementation class by name: the fragment interface name plus the suffix 'Impl'.
When you call repository.save(entity), how does Spring Data decide whether to run an INSERT or an UPDATE by default?
basics
~10 sBy default Spring Data treats an entity as new when its @Id is null (or 0 for a primitive id type). New means INSERT; otherwise it's an existing row, so UPDATE.
You declare a Spring Data repository as just an interface with no body. Who provides the actual implementation, and when?
basics
~20 sYou never write the implementation. Spring Data creates it for you automatically at application startup — it generates a proxy object that implements your repository interface and wires it into the Spring container as a bean.
What are derived query methods in Spring Data, and how does a method name like findByLastName become a query?
basics
~10 sYou declare a method on a repository interface, like findByLastName(String name), and write no body. Spring Data reads the method name and generates the query automatically from it.
What does formLogin() enable in Spring Security, and what is the role of UsernamePasswordAuthenticationFilter?
basics
~10 sformLogin() turns on a browser login form. Spring adds UsernamePasswordAuthenticationFilter, which intercepts the POST to /login, reads the username and password fields, and asks the AuthenticationManager to verify them.
What does Spring Security's logout() DSL configure, and what happens when a user hits /logout?
basics
~10 sThe logout() DSL wires up a LogoutFilter. When a user POSTs to /logout, the filter clears the logged-in user from the SecurityContext, invalidates the HTTP session, and redirects to a success page (default /login?logout).
What is the contract of AuthenticationManager.authenticate()? What are its three possible outcomes?
basics
~10 sAuthenticationManager has one method, authenticate(Authentication). It returns a fully authenticated Authentication if credentials are valid, throws an AuthenticationException if they are invalid, or returns null if it cannot decide.
What is Spring Security's PasswordEncoder and why should you use it instead of storing passwords directly?
basics
~20 sPasswordEncoder is an interface that turns a raw password into a one-way, salted hash. You store the hash, never the plaintext, so a database leak doesn't expose real passwords. Its matches() method verifies a login attempt.
What is UserDetailsService in Spring Security, and what does loadUserByUsername return?
basics
~20 sUserDetailsService is an interface with one method, loadUserByUsername(String), that looks up a user by name and returns a UserDetails object holding the username, encoded password, and authorities (roles). It throws UsernameNotFoundException if no user exists.
What is the Spring Cloud Circuit Breaker abstraction and what problem does it solve?
basics
~10 sIt is a common Spring API (CircuitBreakerFactory / CircuitBreaker) for wrapping risky calls with a circuit breaker. Your code calls the abstraction, and the actual implementation (like Resilience4j) is plugged in separately.
What is Spring Cloud Bus and what problem does it solve?
basics
~20 sSpring Cloud Bus links all instances of your microservices through a shared message broker (Kafka or RabbitMQ). You can then broadcast one message — like 'refresh your config' — to the whole cluster at once instead of calling each instance.
How does a Spring Boot application connect to a Spring Cloud Config Server using spring.config.import, and what does the configserver: prefix do?
basics
~10 sAdd the spring-cloud-starter-config dependency, then set spring.config.import=configserver:http://localhost:8888 in application.yml. On startup the app fetches its properties from that Config Server before creating beans.
In a Spring Cloud Config Server property repository, what does the {cipher} prefix on a property value mean, and what happens to it before the client receives the value?
basics
~20 s{cipher} marks a property value as encrypted at rest in the config repo. By default the Config Server decrypts it and sends the plain value to the client, so the secret never sits in git as plaintext.
What does Spring Cloud Kubernetes do with a ConfigMap, and how does its data reach your beans?
basics
~10 sSpring Cloud Kubernetes reads a Kubernetes ConfigMap (named after your app) and adds its key/value entries to the Spring Environment as a PropertySource, so @Value and @ConfigurationProperties see them like any other property.
In Spring Messaging, what are MessageChannel and MessageHandler, and how do they relate?
basics
~10 sMessageChannel is a pipe you send messages into via send(). MessageHandler is code that receives one message via handleMessage(). A producer sends to a channel; a handler subscribed to that channel processes what arrives.
What is Spring's Message<T> abstraction, and what are its two parts?
basics
~10 sMessage<T> is Spring's generic container for something being sent. It has two parts: a payload (the body of type T) and MessageHeaders (a map of metadata like an id and timestamp).
What is the difference between Spring's ApplicationEventPublisher / @EventListener and the messaging support in spring-messaging (Message / MessageChannel)?
basics
~10 sApplicationEventPublisher with @EventListener sends events between beans inside one running JVM. spring-messaging (Message, MessageChannel) is a broader abstraction for passing messages, often across process boundaries through a broker like Kafka or RabbitMQ.
What is dead-lettering in RabbitMQ/Spring AMQP, and how do you configure a dead-letter exchange on a queue?
basics
~10 sDead-lettering routes messages that can't be processed to a separate exchange instead of losing them. You set the queue arguments x-dead-letter-exchange (and optionally x-dead-letter-routing-key) when declaring the queue.
What are RabbitMQ publisher confirms in Spring AMQP, and what problem do they solve?
basics
~20 sBy default, sending a message via RabbitTemplate doesn't tell you if the broker actually received it. Publisher confirms make the broker send back an async ack (or nack) per message, so the producer knows the send succeeded.
What is the ExecutionContext in Spring Batch, and what is it used for?
basics
~20 sExecutionContext is a persisted key/value map Spring Batch attaches to a running job or step. It stores state — like how many items were read — so if the job stops and restarts, it can pick up where it left off.
In Spring Batch, what is the difference between a JobInstance and a JobExecution?
basics
~20 sA JobInstance is a logical run of a job (job name + its identifying parameters). A JobExecution is a single attempt to run that instance. One JobInstance can have several JobExecutions if earlier attempts failed and were restarted.
In Spring Batch, what are the Job and Step abstractions, and how do they relate?
basics
~20 sA Job is an entire batch process. A Step is one independent phase of it. A Job contains an ordered list of Steps and runs them in sequence; each Step does a unit of work.
In Spring Batch, what is the difference between BatchStatus and ExitStatus?
basics
~20 sBatchStatus is an enum (COMPLETED, FAILED, STARTED, STOPPED...) describing a job's or step's lifecycle state. ExitStatus is a string-code object (exitCode plus description) used mainly to decide flow between steps. Both live on every JobExecution and StepExecution.
What is a StepExecution in Spring Batch, and which metrics/counts does it record?
basics
~10 sA StepExecution represents one attempt to run a Step. It records runtime metrics: readCount, writeCount, filterCount, commitCount, rollbackCount, and skipCount, plus status, timestamps, and its own ExecutionContext.
What is @DynamicPropertySource in Spring Boot testing, and what problem does it solve?
basics
~10 s@DynamicPropertySource marks a static test method that registers property values computed at runtime — like a Testcontainers database's random mapped port or JDBC URL — into Spring's Environment before the application context starts.
What is Spring Boot's @ServiceConnection annotation and what problem does it solve in integration tests?
basics
~20 s@ServiceConnection is a Spring Boot annotation you put on a Testcontainers container. Boot reads the container's real URL, port, username and password and wires your app's beans (like the DataSource) to it automatically, so you don't set those properties by hand.
What is the @Sql annotation in Spring TestContext, and how do you use it to seed data for an integration test?
basics
~20 s@Sql runs SQL scripts (or inline statements) against the test's DataSource before a test method. You point it at a .sql file on the classpath, e.g. @Sql("/data.sql"), to insert seed rows before the test runs.
What is Testcontainers and why use the @Testcontainers / @Container annotations in a JUnit 5 test?
basics
~20 sTestcontainers starts a real service (like PostgreSQL) in a throwaway Docker container for tests. @Testcontainers on the class turns on lifecycle management, and @Container marks a container field so it is started before tests and stopped after.
What is TestEntityManager and why would you use it in a @DataJpaTest instead of your repository?
basics
~20 sTestEntityManager is a Spring Boot test helper auto-configured by @DataJpaTest. It wraps JPA's EntityManager with test-friendly methods (persist, persistAndFlush, persistFlushFind, find, flush, clear) to set up database rows for a test without going through the repository you're testing.
What is the Actuator discovery index at /actuator, and how do you find out which endpoints your running app actually exposes?
basics
~10 sGET /actuator returns a JSON document with a _links section. Each entry maps an endpoint id (like health, metrics, beans) to its URL. It's the menu of endpoints currently exposed over the web.
What do /actuator/health and /actuator/info return, and where does their content come from?
basics
~20 s/actuator/health reports whether the app and its dependencies are healthy, returning a status like UP or DOWN. /actuator/info returns arbitrary descriptive info (build version, git commit) contributed by the app; it is empty unless you configure contributors.
How do you create a basic custom Actuator endpoint in Spring Boot, and what must you do before it becomes reachable over HTTP?
basics
~10 sMake a Spring bean annotated with @Endpoint(id="...") and give it a method annotated @ReadOperation. Then expose it via management.endpoints.web.exposure.include so it appears under /actuator/<id>.
Which Actuator endpoints are reachable over HTTP by default in a Spring Boot app, and how do you expose additional ones?
basics
~10 sBy default only the health endpoint is exposed over the web. To expose more, list their IDs (or * for all) in management.endpoints.web.exposure.include, e.g. include=health,info,metrics.
What is the Actuator /actuator/info endpoint and where does its content come from?
basics
~10 sGET /actuator/info returns arbitrary application info as JSON. Spring Boot builds the response by collecting every InfoContributor bean; each one adds details like build version, git commit, or Java/OS info.
What are the generated `*__BeanDefinitions` source classes that Spring's AOT engine produces at build time, and why are they created?
basics
~20 sDuring an AOT build, Spring generates plain Java classes named like MyService__BeanDefinitions that build each bean's definition in explicit code instead of scanning and reflecting at startup. This lets GraalVM native images work without runtime reflection.
What does it mean that Spring AOT 'freezes' conditions and the bean set at build time?
basics
~20 sDuring an AOT build Spring evaluates all @Conditional/@Profile checks and auto-configuration once, decides which beans exist, and generates code registering exactly those beans. Those decisions are fixed; they are not re-checked when the app runs.
What does the Spring Boot bootBuildImage task do, and how do you make it produce a native-image container?
basics
~10 sbootBuildImage is a Spring Boot build task that packages your app into a Docker/OCI container using Cloud Native Buildpacks. To build a native executable inside it, set the environment variable BP_NATIVE_IMAGE=true for the buildpack.
What is the GraalVM native-build-tools Gradle plugin, and which tasks does it add to a Spring Boot build?
basics
~10 sIt's the Gradle plugin org.graalvm.buildtools.native that lets you compile a GraalVM native image locally. It adds tasks like nativeCompile (build the native executable) and nativeRun (run it).
What is the GraalVM native-maven-plugin and how do you use it to build a native image of a Spring Boot app with Maven?
basics
~10 sIt's the GraalVM native-build-tools Maven plugin that compiles your app into a native executable. In Spring Boot you run mvn -Pnative native:compile; the native profile plus its native:compile goal invoke GraalVM's native-image compiler.
What is Spring AI's ChatClient, and how do you make a basic call to a model with it?
basics
~10 sChatClient is Spring AI's fluent client for talking to an LLM. You write chatClient.prompt().user("...").call().content() to send a user message and get the reply back as a String.
What is Spring AI's ChatMemory abstraction and why is it needed when talking to an LLM?
basics
~20 sLLM calls are stateless — the model forgets previous turns. ChatMemory is a Spring AI interface that stores a conversation's past messages and replays them into each new request, so the model appears to remember the dialogue.
What is an EmbeddingModel in Spring AI and what does it produce?
basics
~10 sEmbeddingModel is a Spring AI interface that turns text into an embedding — a list of floating-point numbers (a vector) representing the text's meaning. Similar texts get numerically similar vectors, which powers semantic search.
In Spring AI, what is a Prompt, and what roles do SystemMessage and UserMessage play inside it?
basics
~10 sA Prompt is the request sent to the model: a list of Messages plus optional options. A SystemMessage sets the model's behavior/persona; a UserMessage carries the user's actual input.
What is RAG in Spring AI, and what does the QuestionAnswerAdvisor do?
basics
~10 sRAG (Retrieval-Augmented Generation) fetches relevant documents from a vector store and adds them to the prompt so the LLM answers from your data. Spring AI's QuestionAnswerAdvisor does this automatically on each ChatClient call.