Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: 5–8 Years

Revise the 2–5 Years Tier

  • Revise: Core Java & Java 8+ (2–5 Years Tier)
  • Revise: Multithreading & Concurrency (2–5 Years Tier)
  • Revise: Spring Framework, Spring Boot & Security (2–5 Years Tier)
  • Revise: Kafka, Git/Maven/Gradle, Deployment & Testing (2–5 Years Tier)

Advanced Core Java

  • Advanced OOP & Design Scenarios — Interview Questions
  • Advanced Concurrency, Collections & Memory — Interview Questions
  • Modern Java Language Features & Annotations — Interview Questions
  • Class Loading, Reflection, Serialization & Idioms — Interview Questions

Java Design Patterns in Depth

  • Design Patterns Overview & Singleton — Interview Questions
  • Factory & Abstract Factory Patterns — Interview Questions
  • Builder & Prototype Patterns — Interview Questions
  • Adapter & Bridge Patterns — Interview Questions
  • Composite & Decorator Patterns — Interview Questions
  • Facade & Proxy Patterns — Interview Questions
  • Chain of Responsibility & Observer Patterns — Interview Questions
  • Strategy & Template Method Patterns — Interview Questions
  • Command Pattern — Interview Questions

Advanced Spring Boot

  • Logging, Configuration & Actuator (Advanced) — Interview Questions
  • Transactions, Multiple Datasources & Query Tuning — Interview Questions
  • Validation & REST API Design (Advanced) — Interview Questions
  • Reactive, Async & Scheduling in Spring Boot — Interview Questions
  • Deployment, High Availability, Scaling & Caching — Interview Questions
  • Custom Starters, DI, Testing & DevTools — Interview Questions

Spring Security for APIs

  • Securing REST APIs End to End — Interview Questions

Microservices at Scale

  • Monolith Migration, Communication & Spring Cloud — Interview Questions
  • Data Consistency, Sagas & Kafka Messaging — Interview Questions
  • Tracing, Discovery, Load Balancing, Service Mesh & Resilience — Interview Questions
  • Deployment, Scaling & Security for Microservices — Interview Questions

Microservice Design Patterns

  • API Gateway, Circuit Breaker & Retry Patterns — Interview Questions
  • Service Discovery & Database per Service Patterns — Interview Questions
  • Saga, Choreography & Orchestration Patterns — Interview Questions
  • Bulkhead & Strangler Fig Patterns — Interview Questions
Chaturmind
← Java Interview Prep: 5–8 Years

Revise the 2–5 Years Tier

  • Revise: Core Java & Java 8+ (2–5 Years Tier)
  • Revise: Multithreading & Concurrency (2–5 Years Tier)
  • Revise: Spring Framework, Spring Boot & Security (2–5 Years Tier)
  • Revise: Kafka, Git/Maven/Gradle, Deployment & Testing (2–5 Years Tier)

Advanced Core Java

  • Advanced OOP & Design Scenarios — Interview Questions
  • Advanced Concurrency, Collections & Memory — Interview Questions
  • Modern Java Language Features & Annotations — Interview Questions
  • Class Loading, Reflection, Serialization & Idioms — Interview Questions

Java Design Patterns in Depth

  • Design Patterns Overview & Singleton — Interview Questions
  • Factory & Abstract Factory Patterns — Interview Questions
  • Builder & Prototype Patterns — Interview Questions
  • Adapter & Bridge Patterns — Interview Questions
  • Composite & Decorator Patterns — Interview Questions
  • Facade & Proxy Patterns — Interview Questions
  • Chain of Responsibility & Observer Patterns — Interview Questions
  • Strategy & Template Method Patterns — Interview Questions
  • Command Pattern — Interview Questions

Advanced Spring Boot

  • Logging, Configuration & Actuator (Advanced) — Interview Questions
  • Transactions, Multiple Datasources & Query Tuning — Interview Questions
  • Validation & REST API Design (Advanced) — Interview Questions
  • Reactive, Async & Scheduling in Spring Boot — Interview Questions
  • Deployment, High Availability, Scaling & Caching — Interview Questions
  • Custom Starters, DI, Testing & DevTools — Interview Questions

Spring Security for APIs

  • Securing REST APIs End to End — Interview Questions

Microservices at Scale

  • Monolith Migration, Communication & Spring Cloud — Interview Questions
  • Data Consistency, Sagas & Kafka Messaging — Interview Questions
  • Tracing, Discovery, Load Balancing, Service Mesh & Resilience — Interview Questions
  • Deployment, Scaling & Security for Microservices — Interview Questions

Microservice Design Patterns

  • API Gateway, Circuit Breaker & Retry Patterns — Interview Questions
  • Service Discovery & Database per Service Patterns — Interview Questions
  • Saga, Choreography & Orchestration Patterns — Interview Questions
  • Bulkhead & Strangler Fig Patterns — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: 5–8 YearsRevise the 2–5 Years Tier
✓ FreeAdvanced· 53 min read

Revise: Spring Framework, Spring Boot & Security (2–5 Years Tier)

Every 2–5-year Spring question — bean lifecycle, scopes, AOP, transactions, Boot auto-configuration, profiles, Actuator, Spring Security and JWT — as one-line answers linked to the full answers.

Published September 25, 2026


How to use this revision

This page condenses every question from the 2 to 5 Years course in these areas into a single line: the question, linked to its full answer, and the one-sentence answer you should be able to give instantly. Read down the list and answer each question aloud before reading the line. Wherever you hesitate, follow the link and revise the full answer — interviewers at your level expect these basics to be fluent, and they often open with them before going deeper.

Spring Framework In Depth

Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions — open the lesson

  • Explain the Spring bean lifecycle, and why it matters in a large application. — For a singleton bean, the container: Instantiates it (constructor injection happens here); Populates its properties (setter and field injection); Calls the Aware callbacks (BeanNameAware, ApplicationContextAware…); Runs BeanPostProcessor.postProcessBeforeInitialization; …
  • What are the differences between ApplicationContext and BeanFactory? — BeanFactory is the basic IoC container. It creates beans lazily on request, and supports DI. ApplicationContext extends it, adding: eager singleton creation (fail fast at startup); automatic registration of BeanPostProcessors and BeanFactoryPostProcessors, which is…
  • When would you use BeanFactory, and when ApplicationContext? — Use ApplicationContext in practically every application. Spring Boot always creates one. A bare BeanFactory makes sense only in very constrained environments, or in framework code that needs minimal, lazy bean management.
  • What is a circular dependency? — Bean A needs bean B, and bean B (directly or through a chain) needs A. With constructor injection, Spring can't create either one first, so startup fails with BeanCurrentlyInCreationException ("Is there an unresolvable circular reference?").
  • What ways does Spring Boot offer to resolve circular dependencies? — In order of preference: Redesign. Extract the shared logic into a third bean that both depend on, or replace the back-reference with an event (ApplicationEventPublisher); Inject a lazy proxy: @Lazy on one constructor parameter, or ObjectProvider<B>, resolved when first…
  • What's the difference between @Component and @Service? Are they interchangeable? — @Service is a specialisation of @Component (it's meta-annotated with it), so both register a bean through component scanning, and they're technically interchangeable.
  • What's the difference between JpaRepository and CrudRepository, and when would you use CrudRepository? — The hierarchy is CrudRepository → ListCrudRepository → JpaRepository, with PagingAndSortingRepository alongside.
  • What's the difference between @Qualifier and @Primary? (And again: are @Component and @Service interchangeable?) — @Primary marks the default bean when several beans match a type; @Qualifier("name") at the injection point explicitly chooses one, and it overrides @Primary.
  • How is @Transactional used? — Put @Transactional on a public method of a Spring bean, usually in the service layer. Spring's proxy begins a transaction before the method, commits if it returns normally, and rolls back on RuntimeException or Error.
  • What are Spring profiles, and how do you start an application with one? — Profiles are named groups of configuration and beans (dev, test, prod) that are activated per environment. Beans can carry @Profile, and properties can live in application-{profile}.yml. Activate them with any of: --spring.profiles.active=prod (a command-line…
  • How do you inject properties from environment variables? — Spring's Environment already includes the OS environment variables, so @Value("${DB_PASSWORD}") works. Better still, rely on relaxed binding: the environment variable PAYMENTS_BASE_URL automatically binds to the property payments.base-url, and so to a…

Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions — open the lesson

  • Scenario: two beans conflict in your application. How do you resolve it in Spring Boot? — First, identify the kind of conflict: Two beans of the same type (NoUniqueBeanDefinitionException): mark the default with @Primary, or pick one at the injection point with @Qualifier. Or inject a List/Map of all of them, and choose at runtime; Two bean definitions…
  • What happens if several auto-configuration classes define the same bean? — Well-written auto-configurations guard their beans with @ConditionalOnMissingBean. The first one to be evaluated registers the bean, and the others back off.
  • XML or annotations for configuration: which do you prefer, and why? — Annotations and Java configuration. They're type-safe (refactoring and IDE navigation work), sit next to the code they configure, can use conditions and profiles in code, and are what Spring Boot is designed around.
  • What's the difference between @Spy and @Mock in Mockito? — A @Mock is a complete fake. Every method returns a default (null, 0, an empty collection) unless you stub it, and no real code runs.
  • What's the difference between a join point and a pointcut in Spring AOP? — A join point is a point in program execution where an aspect could apply. In Spring AOP, it's always a method execution on a Spring bean.
  • What is Spring Batch used for? Describe how you'd implement a batch job. — Spring Batch processes large volumes of data reliably in the background: nightly settlements, file imports, report generation, data migrations.
  • What kind of injection does @Autowired perform? — @Autowired resolves a dependency by type. If several beans match, it narrows the choice using @Qualifier, then @Primary, then the parameter or field name as a fallback.
  • Why is constructor injection recommended over setter injection? — Required dependencies are enforced, so the object can never exist half-configured; final fields make it immutable, and safe to publish across threads; It's easily testable without Spring: new Service(mockA, mockB); It makes design problems visible: a ten-argument…
  • Define AOP, and state its biggest disadvantage. — Aspect-Oriented Programming modularises cross-cutting concerns (transactions, security, logging, metrics, caching, retries) into aspects that are applied declaratively, instead of being scattered through the business code.
  • How can you prevent cyclic dependencies in Spring? — Design with clear layering: controllers → services → repositories, with dependencies flowing one way; Give each service a single responsibility. Extract shared logic into its own component; Communicate "upwards" with events (ApplicationEventPublisher) instead of direct…

Spring Boot In Depth & Scenarios

Spring Boot Internals & Auto-Configuration — Interview Questions — open the lesson

  • What are conditional annotations, and why does Spring Boot need them? — Conditional annotations register a bean or configuration class only if a condition holds when the context starts.
  • What does @EnableAutoConfiguration do, and how does auto-configuration work internally? — @EnableAutoConfiguration imports AutoConfigurationImportSelector. At startup, that selector: Reads the candidate classes listed in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports in every JAR. (Before Boot 2.7, the list was in…
  • How do you handle multiple beans of the same type? — @Primary marks the default; @Qualifier("name"), or a custom qualifier annotation, chooses a specific bean; Inject all of them (List<T>, Map<String, T>), and pick dynamically (the strategy pattern); Use ObjectProvider<T> for optional or lazy resolution.
  • How does Spring Boot decide which web server to use, and what if there's none? — Boot first decides the application type: servlet, if Spring MVC and the Servlet API are on the classpath; reactive, if WebFlux is present without MVC; none, otherwise.
  • How do you list all the beans in the application? — Inject the ApplicationContext and call getBeanDefinitionNames(), or getBeansOfType(X.class) for one type.
  • Explain Spring Boot's embedded servlet containers. — The server (Tomcat, Jetty, Undertow) runs inside your application as a library. SpringApplication creates a ServletWebServerApplicationContext, which obtains a ServletWebServerFactory bean, starts the server, and registers the DispatcherServlet and filters as beans.
  • How does Spring Boot make dependency injection easier than traditional Spring? — The DI mechanism is the same. What Boot removes is the configuration work around it: @SpringBootApplication turns on component scanning from the root package; Auto-configuration supplies the infrastructure beans you'd otherwise declare by hand (the DataSource,…
  • What is the Spring Boot CLI, and how is it used today? — The CLI is a command-line tool, installed with SDKMAN or Homebrew. In Boot 3 it's mainly a project generator: spring init --dependencies=web,data-jpa,actuator --java-version=21 my-service creates a project from Spring Initializr.
  • How do you disable a specific auto-configuration? — Use @SpringBootApplication(exclude = DataSourceAutoConfiguration.class), excludeName = "…" for classes that may not be on the classpath, or the property spring.autoconfigure.exclude=… (which can vary by profile).
  • Can you create a non-web application with Spring Boot? — Yes. Leave out the web starters, or set spring.main.web-application-type=none. The context starts, runs your CommandLineRunners, @Scheduled jobs or message listeners, and the JVM keeps running for as long as non-daemon threads are alive (a Kafka consumer, for example).
  • What does @SpringBootApplication do internally? — It combines: @SpringBootConfiguration: a @Configuration that Boot's test support can find; @EnableAutoConfiguration: the import selector described above; @ComponentScan, with Boot's TypeExcludeFilter and AutoConfigurationExcludeFilter, so auto-configuration…
  • How does an auto-configuration "back away" when your bean exists? — It declares its bean method with @ConditionalOnMissingBean. Your configuration is processed before auto-configurations, so by the time the condition is evaluated your bean is already registered.
  • Can you replace the embedded Tomcat server? — Yes. Exclude spring-boot-starter-tomcat from the web starter, and add spring-boot-starter-jetty or spring-boot-starter-undertow.
  • What are the basic annotations Spring Boot applications use? — Bootstrap: @SpringBootApplication; Components: @Component, @Service, @Repository, @Controller/@RestController; Configuration: @Configuration, @Bean, @ConfigurationProperties, @Value, @Profile, @Conditional…; Web: @RequestMapping and its shortcuts,…

Spring Boot Configuration, Profiles & Secrets — Interview Questions — open the lesson

  • What advantages does YAML have over .properties, and what are its limitations? — YAML is hierarchical, so it's less repetitive and more readable for nested and list configuration. It supports multi-document files (---), for per-profile sections. Its limitations: It's indentation-sensitive (a misplaced space silently changes the meaning); Implicit typing…
  • How do Spring Boot profiles work? — A profile is a named set of beans and properties that's active only when the profile is: Properties: application-{profile}.yml files, or sections of a multi-document YAML file guarded by spring.config.activate.on-profile. They override the default application.yml; Beans…
  • Why use profiles? — The same artifact can then run in every environment. Only the configuration changes, so you test exactly the binary you ship.
  • How does Spring Boot help manage secrets and sensitive configuration across environments? — Externalised configuration, so secrets never live in the code or JAR. They come from environment variables, mounted files, or a secrets store; Config-tree support (spring.config.import=configtree:/run/secrets/) reads Kubernetes secret volumes as properties; Integrations…
  • How would you manage externalised configuration and secure sensitive properties in a microservices architecture? — Centralise non-secret configuration, either in Spring Cloud Config Server (backed by Git, versioned and audited) or in a platform-native equivalent (Kubernetes ConfigMaps plus GitOps); Keep secrets in a dedicated secrets manager (Vault or a cloud secrets manager), accessed…
  • How does Spring Boot support internationalization (i18n)? — Boot auto-configures a MessageSource when it finds messages.properties (plus messages_hi.properties, messages_fr.properties…) on the classpath.
  • What does "relaxed binding" mean? — When binding to @ConfigurationProperties, Boot accepts several spellings of the same property name, so the same setting can come from YAML, a system property or an environment variable.
  • Scenario: your app behaves differently in development and production. How do you manage the differences with profiles? — Keep shared defaults in application.yml; Put environment overrides in application-dev.yml and application-prod.yml, or better, inject environment values through environment variables; Switch beans with @Profile: a stub payment gateway in dev, and a real one in…
  • Scenario: the app must switch between several data sources at runtime, based on the request (for example, per region or tenant). How do you implement it? — Use Spring's AbstractRoutingDataSource, which wraps several target DataSources and chooses one per connection through determineCurrentLookupKey(); Store the routing key in a ThreadLocal context, set by a filter or interceptor from the request (a header, JWT claim or…

Spring Boot Data, Transactions & Caching — Interview Questions — open the lesson

  • What caching mechanisms does Spring Boot provide? — Spring's cache abstraction: annotations (@Cacheable, @CachePut, @CacheEvict, @Caching) applied through AOP proxies to bean methods, backed by a pluggable CacheManager. Boot auto-configures the provider it finds: Caffeine: an in-process cache with size, TTL and…
  • How would you implement caching in a Spring Boot application? — Add spring-boot-starter-cache plus a provider (Caffeine or Redis); Add @EnableCaching; Annotate read methods with @Cacheable; Keep the cache correct with @CacheEvict/@CachePut on writes, plus a TTL as a safety net; …
  • How does Spring Boot simplify the data-access layer? — Auto-configuration: the DataSource with a HikariCP pool, EntityManagerFactory, transaction manager and JPA settings, all from spring.datasource.* and spring.jpa.*; Spring Data repositories: CRUD, paging, derived queries (findByStatusAndCreatedAtAfter), @Query,…
  • What are the best practices for managing transactions in Spring Boot? — Put @Transactional on service-layer methods (the business unit of work), not on controllers or repositories; Keep transactions short. No remote calls, message sends or file I/O inside them. Use the outbox pattern for events that must be consistent with the database change;…
  • What's the difference between cache eviction and cache expiration? — Eviction removes entries to respect a capacity limit, chosen by a policy (LRU, LFU, or W-TinyLFU in Caffeine), and is triggered by space pressure.
  • How do you implement pagination in a Spring Boot application? — Accept a Pageable (?page=0&size=20&sort=createdAt,desc), pass it to a Spring Data method, and return the content plus page metadata.
  • How would you implement soft delete for audit purposes? — Add a deleted flag, or better, a deleted_at timestamp. Intercept deletes, so they become updates, and filter deleted rows out of every query — @Entity @SQLDelete(sql = "UPDATE customer SET deleted_at = now() WHERE id = ? AND version = ?")
  • Scenario: design a REST API for managing user data. How do you structure the application? — A layered, feature-oriented structure: Controller (UserController): HTTP mapping, request and response DTOs, @Valid validation, status codes (201 with Location, 204, 404). No business logic; Service (UserService): business rules (a unique email, password hashing),…

Spring Boot Testing, Error Pages & Deployment — Interview Questions — open the lesson

  • How do you approach testing a Spring Boot application? — Use a test pyramid: Many unit tests: JUnit 5 and Mockito, with no Spring context. They cover domain logic and services, and run in milliseconds; Some slice tests that load only one layer:; A few integration tests: @SpringBootTest with Testcontainers (a real PostgreSQL or…
  • How are @SpringBootTest and @MockBean used? — @SpringBootTest boots the full application context. Add webEnvironment = RANDOM_PORT to start the real server, for HTTP tests with TestRestTemplate or WebTestClient.
  • What is Spring Boot DevTools used for? — DevTools speeds up local development: Automatic restarts when classes change. It uses two class loaders, so only your code reloads, which is fast; LiveReload, for browser refreshes; Development-friendly defaults, such as template caching turned off; Global settings.; …
  • How do you mock external services in a Spring Boot test? — Choose the level to mock at: The bean level: @MockitoBean replaces your client bean (for example, PaymentGateway). It's fast, but it skips the HTTP and serialisation code; The HTTP level: WireMock (or MockRestServiceServer for RestTemplate/RestClient) runs a fake…
  • How do you mock other microservices during testing? — Integration tests: WireMock stubs for the downstream services, which also let you simulate slow responses, 5xx errors and timeouts, to test resilience; Contract testing: Pact (consumer-driven) or Spring Cloud Contract. The consumer's expectations become a contract that the…
  • How do you create a Docker image for a Spring Boot application? — You have three options: Cloud Native Buildpacks: ./mvnw spring-boot:build-image. No Dockerfile is needed, and you get layered, reproducible, non-root images with memory-calculator tuning; Jib: builds optimised images without a Docker daemon; A multi-stage Dockerfile using…
  • How do you deploy a Spring Boot web app as a JAR, and as a WAR? — JAR (the default): ./mvnw package creates an executable fat JAR with an embedded server. Run it with java -jar app.jar, or containerise it; WAR: set <packaging>war</packaging>, mark the embedded Tomcat starter as provided, and make the main class extend…
  • How do you integrate a Spring Boot application with a CI/CD pipeline? — A typical pipeline (GitHub Actions, GitLab CI or Jenkins): Build and unit test (./mvnw verify), with caching of ~/.m2; Static analysis and security: Checkstyle/Spotless, SonarQube, dependency scanning (OWASP, Snyk), and secret scanning; Integration tests with…
  • What is the Whitelabel error page, and how do you replace it? — It's Spring Boot's default HTML error view, rendered by BasicErrorController at /error when an error isn't handled and no custom error page exists.
  • How do you handle a 404 in Spring Boot? — For missing resources your code looks up (such as an order that doesn't exist), throw a domain exception (OrderNotFoundException), or ResponseStatusException(NOT_FOUND), and map it in @RestControllerAdvice; For unmapped URLs, Spring Framework 6.1+ raises…
  • Scenario: deploy a Spring Boot app to AWS or Azure. What steps do you take, and how do you configure the different environments? — Package a container image, or a JAR; Choose a runtime:; Provision the database, cache and network with IaC (Terraform), in private subnets; Configure the environments with environment variables plus profiles. Keep secrets in AWS Secrets Manager / Parameter Store or Azure Key…

Spring Boot Performance, Scaling & Resilience — Interview Questions — open the lesson

  • Your Spring Boot app slows down under high load. How do you find and fix the problem? — Follow a loop: observe → reproduce → locate → fix → verify.
  • Performance issues under high load: describe your first 30 minutes. (A common rephrasing) — Minute 0–5: check the dashboards. Did latency rise for all endpoints (a shared resource: database, pool, GC, CPU) or one (that endpoint's code or dependency)? Was there a deployment or configuration change?; Minute 5–15: take thread dumps and pool metrics. Many threads…
  • What strategies would you use to optimise a Spring Boot application's performance? — Group them by where the time goes.
  • What strategies would you use to optimise performance? (Asked again: which would you try first?) — The cheapest, highest-impact fixes first: Query fixes (N+1, indexes). These are often 10–100× wins; Timeouts and pool sizing, which stop pile-ups; Caching hot reads; Moving non-critical work off the request path (events or queues for emails and analytics).
  • Describe a Spring Boot project where you significantly improved performance. — *"Order-history requests hit p99 of 4 s at peak. Tracing showed about 300 SQL queries per request, an N+1 on order lines and products.
  • How would you scale a Spring Boot application to handle high traffic? — Make the app stateless: no in-memory sessions or local-only caches for correctness; Scale horizontally behind a load balancer; Autoscale: Kubernetes HPA on CPU, or custom metrics such as requests per second or queue lag; Protect the data tier: connection limits (instances ×…
  • How would you scale for high traffic? (Follow-up: what breaks first when you add instances?) — Usually the database. Twenty instances with a pool of 20 connections each means 400 connections, which can exceed database limits or thrash it. Other things that break: In-memory state: sessions, caches, and scheduled jobs that now run on every instance (use ShedLock or a…
  • How is session management configured in distributed systems? — Prefer stateless authentication (JWT or opaque OAuth2 tokens validated by each service), so there's no session to share.
  • How can Spring Boot applications be made more resilient to failures in a microservices architecture? — Assume every dependency will fail, and contain the damage with Resilience4j (Spring Cloud Circuit Breaker): Timeouts on every remote call: HTTP client connect and read timeouts, plus TimeLimiter; Retries with exponential backoff and jitter, for idempotent operations only;…

Spring Boot Async, Events & Messaging — Interview Questions — open the lesson

  • How would you handle inter-service communication in Spring Boot microservices? — Match the style to the need: Synchronous queries (the answer is needed now): RestClient (Spring 6.1+, the modern blocking client), Spring Cloud OpenFeign (declarative interfaces), or WebClient in reactive apps. For internal high-throughput calls, gRPC. Always with…
  • How does Spring Boot handle asynchronous operations? — With @EnableAsync and @Async, a method call is intercepted by a proxy, and executed on a TaskExecutor instead of the caller's thread.
  • How do you enable and use @Async correctly? — Add @EnableAsync; Annotate a public method on a Spring bean with @Async; Call it from another bean, because self-invocation bypasses the proxy; Configure a bounded executor; …
  • After a user registers, you must send a welcome email. How would you implement it? — Send it after the registration transaction commits, asynchronously, with retries. That way, a slow or failing mail server never breaks registration, and you never email someone whose registration was rolled back.
  • How would you manage and monitor asynchronous tasks, tracking progress and handling failures? — In-process tasks (@Async):; Long-running or important jobs: persist job state in a database table (PENDING/RUNNING/DONE/FAILED, progress, attempts), so it survives restarts and can be queried by users (GET /jobs/{id}). Retry failures with backoff, and alert on stuck or…
  • You need to process notifications asynchronously through a message queue. How do you set up the integration? — Add spring-kafka, and configure spring.kafka.bootstrap-servers, the serializers and a consumer group; Produce with KafkaTemplate.send(topic, key, event), keyed by user ID so each user's messages stay in order; Consume with @KafkaListener, making processing idempotent,…
  • How can Spring Boot be used to build an event-driven architecture? — At two levels: Inside one service: application events. Publish with ApplicationEventPublisher.publishEvent(anyObject) (since Spring 4.2, events don't need to extend ApplicationEvent), and handle them with @EventListener, or @TransactionalEventListener (tied to commit…
  • Scenario: design a Spring Boot backend that processes real-time streams from thousands of IoT devices. — Ingest: devices send data over MQTT (to a broker such as EMQX or HiveMQ, or AWS IoT Core) or HTTP. A bridge pushes the readings into Kafka, partitioned by device ID, so each device's readings stay in order; Process: stateless Spring Boot consumers validate and enrich the…
  • How would you use application events to notify different parts of your application? — Define event records that describe facts (OrderPlaced, PaymentFailed); Publish them where the fact happens; Let each interested module listen, without the publisher knowing who consumes the event.

Spring Boot Security Scenarios — Interview Questions — open the lesson

  • How do you secure the Actuator endpoints? — Expose only what you need. Only health is exposed over HTTP by default. Add endpoints deliberately (management.endpoints.web.exposure.include=health,info,prometheus); Require authentication and an operations role for everything except health and readiness; Isolate the…
  • How would you secure sensitive data accessed by users with different roles? — Layer the defences: Strong authentication: OIDC/SSO, MFA for privileged roles; Authorisation at URL and method level: @PreAuthorize, including ownership checks ("users can read only their own records"), not just roles; Data minimisation: DTOs per role, and field masking…
  • Sensitive data with multiple roles: what about the database and logs? (The same scenario, with a follow-up) — Database: encrypt sensitive columns (with JPA AttributeConverters and keys held in a KMS), and use row-level security or tenant filters where appropriate. Give the application a least-privilege DB user; Logs: mask PII and secrets in logging (Logback masking patterns), and…
  • What's the difference between authentication and authorization in Spring Security? — Authentication establishes who the caller is (a password, token or certificate). It produces an Authentication in the SecurityContext.
  • How is Spring Security implemented in a Spring Boot application? — Add spring-boot-starter-security. Every endpoint is secured by default, with a generated password; Declare a SecurityFilterChain bean that sets the URL rules and the authentication mechanism; Provide users through a UserDetailsService (a database) or an external…
  • How would you secure a microservices architecture with Spring Boot and Spring Security? — A central identity provider (Keycloak, Okta, Auth0, Cognito) issues OAuth2/OIDC tokens; The API gateway validates tokens at the edge, and applies rate limits; Every service is itself an OAuth2 resource server. It validates the JWT's signature and claims (with JWKS key…
  • How do you configure Spring Security against common security concerns? — Map each threat to a control.
  • How would you secure a Spring Boot app with JWT? — Let an identity provider issue the tokens, and configure the app as an OAuth2 resource server. Spring validates the signature (fetching keys from the issuer's JWKS endpoint), expiry, issuer and audience on every request, and maps scopes or roles to authorities.
  • Configure basic form-based authentication so that only logged-in users reach certain endpoints. — ```java @Bean SecurityFilterChain web(HttpSecurity http) throws Exception { return http .authorizeHttpRequests(a -> a .requestMatchers("/", "/login", "/css/").permitAll() .requestMatchers("/account/").authenticated() .anyRequest().authenticated()) .formLogin(f ->…
  • How would you implement rate limiting on API endpoints? — At the edge: Spring Cloud Gateway's RequestRateLimiter (a Redis token bucket), NGINX/Envoy, or an API gateway service; In the application: Bucket4j (a token bucket) in a filter or interceptor. Key it by API key, user or IP. Store the buckets in Redis (or Hazelcast), so the…
  • Your backend must accept cross-origin requests from one specific frontend domain. How do you configure CORS? — Allow exactly that origin, the methods and headers it needs, and credentials only if required. Configure it globally, and make sure Spring Security applies it too.
  • Securing sensitive data for different roles: what would you audit and monitor? (Another variant of the question) — Audit every read and change of sensitive records (who, what, when, from where), in append-only storage; Alert on anomalies: bulk exports, access outside business hours, repeated 403s; Review role assignments periodically, and remove unused privileges; Monitor authentication…
  • What security challenges are specific to WebSockets in Spring Boot? — Authentication happens only at the handshake. Long-lived connections outlive the token, so re-validate, or drop connections when the token expires; Cross-Site WebSocket Hijacking. Browsers send cookies with the handshake, so check the Origin header (setAllowedOrigins);…

Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions — open the lesson

  • What are the Spring Boot Actuator endpoints? — Actuator exposes operational endpoints under /actuator.
  • What is aspect-oriented programming in Spring? — AOP moves cross-cutting concerns (transactions, security, caching, metrics, auditing, retries) out of business methods and into aspects.
  • What is Spring Cloud, and how does it help with microservices? — Spring Cloud is an umbrella of projects, released as a release train aligned with Spring Boot versions, that implements common distributed-system patterns.
  • How does Spring Cloud Function turn business logic into serverless functions? — You write business logic as plain java.util.function beans: a Function<I,O>, Supplier<O> or Consumer<I>.
  • How do you configure Spring Cloud Gateway for routing, security and monitoring? — Routing: routes with predicates (path, host, header, method, weight) and filters (rewrite path, add headers, retries, circuit breaker, request rate limiter), defined in YAML or the Java DSL. Use lb://service-id for discovery-based load balancing; Security: make the gateway…
  • How do you integrate distributed tracing in Spring Boot for monitoring and troubleshooting? — In Spring Boot 3, tracing is provided by Micrometer Tracing, with a bridge to OpenTelemetry (or Brave), and an exporter (OTLP to Jaeger, Tempo, Zipkin or a vendor).

External APIs, Files, GraphQL & WebFlux — Interview Questions — open the lesson

  • What are the best practices for versioning REST APIs in Spring Boot? — Pick one strategy and apply it consistently. URI versioning (/api/v1/...) is the most common and operationally simplest. Header or media-type versioning (Accept: application/vnd.shop.v2+json) keeps URLs clean, but is harder to test and cache. Beyond the mechanism: Version…
  • You're building a file-upload endpoint. How do you handle the upload, and where do you store the files? — Handle: @PostMapping(consumes = MULTIPART_FORM_DATA_VALUE) with a MultipartFile. Validate the size, type (by magic bytes, not just the extension) and name. Stream the content (getInputStream()), never getBytes() for large files. Generate your own storage key; Store:…
  • Your app calls several external APIs. How do you handle their rate limits and failures? — Wrap each client in its own resilience policy: Timeouts: connect and read, per API; Client-side rate limiting (Resilience4j RateLimiter, or a shared Redis bucket across instances), to stay under each provider's quota; Retries with exponential backoff and jitter, only for…
  • Multiple external APIs: how do you handle rate limits and failures? (Follow-up: what if the API is critical and has no fallback?) — Then decouple in time. Accept the request, persist it, and process it asynchronously from a queue, retrying until the API recovers, while telling the user it's "processing".
  • How would you integrate cloud file storage into a Spring Boot app? — Use the provider SDK (AWS SDK v2 S3Client, or Spring Cloud AWS's S3Template), wrapped in your own FileStorage interface, so the rest of the app doesn't depend on the vendor, and tests can use a fake or LocalStack.
  • How would you build a non-blocking, reactive REST API with Spring WebFlux? — Use spring-boot-starter-webflux (Netty), with controllers that return Mono<T>/Flux<T>, and make the whole chain non-blocking: R2DBC or reactive Mongo/Redis for data; WebClient for outbound HTTP; reactive Kafka if needed.
  • How would you consume an external REST API: RestTemplate or WebClient? — In new code, use neither by default: RestClient (Spring 6.1+) is the modern synchronous client, with a fluent API; HTTP interface clients (@HttpExchange) give declarative, Feign-like interfaces; WebClient is for reactive or non-blocking applications; RestTemplate…
  • Build a simple app with a static homepage and a dynamic page showing the server time. What's the project structure? — ``` src/main/java/com/example/site/ SiteApplication.java (@SpringBootApplication) web/TimeController.java (@Controller, GET /time) src/main/resources/ static/index.html (served as-is at "/") static/css/site.css templates/time.html (Thymeleaf view, rendered per request)…
  • How would you add a GraphQL API to an existing Spring Boot REST service? — Use Spring for GraphQL (spring-boot-starter-graphql), the official project built on GraphQL Java: Write the schema in src/main/resources/graphql/schema.graphqls; Implement controllers with @QueryMapping, @MutationMapping and @SchemaMapping, reusing your existing…
  • How do you handle large file uploads efficiently, and keep the system responsive? — Don't route large files through your app servers at all: The client asks your API for a pre-signed upload URL, or a multipart upload; The client uploads directly to object storage, in resumable chunks; Storage emits an event (S3 → SQS/EventBridge), and a background worker…
  • How do you consume an external service with WebFlux, and process the data reactively? — Use WebClient to get a Flux or Mono, then compose operators: map, filter, flatMap with bounded concurrency, buffer/window for batching, and timeout, retryWhen(Retry.backoff(...)) and onErrorResume for resilience.

Spring Security

Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions — open the lesson

  • How does Spring Security integrate with OAuth2? — An application can play one or more of three OAuth2/OIDC roles, each with its own starter: OAuth2 Client (spring-boot-starter-oauth2-client): oauth2Login() sends users to an identity provider (Google, Keycloak, Okta) using the authorization-code flow, and obtains tokens.…
  • What is CORS, and how do you configure it in a Spring Boot app? — Cross-Origin Resource Sharing is a browser mechanism. By default, browsers block JavaScript from reading responses from a different origin (scheme, host and port).
  • What are SecurityContext and SecurityContextHolder? — The SecurityContext holds the current Authentication: the principal, credentials (usually erased after login), and the granted authorities.
  • What is the OAuth2 authorization-code grant? — The standard flow for users logging in through a browser: The app redirects the user to the authorization server's login and consent page; The user authenticates there. The app never sees the password; The authorization server redirects back with a short-lived, one-time…
  • How does Spring Security protect against CSRF, and when can you disable it? — Spring issues a CSRF token (stored in the session, or in a cookie through CookieCsrfTokenRepository), and requires it on state-changing requests (POST, PUT, PATCH, DELETE), as a form field or header.
  • How do you implement method-level security, and what are the advantages? — Enable it with @EnableMethodSecurity, then annotate service methods: @PreAuthorize and @PostAuthorize, with SpEL; @PreFilter and @PostFilter; @Secured and JSR-250's @RolesAllowed, when enabled.
  • Your organisation routes requests through an API gateway. How would you use Spring Security to authenticate and authorise requests at the gateway? — Configure Spring Cloud Gateway as an OAuth2 resource server that validates JWTs, applies coarse-grained rules per route (the scopes or roles needed for /admin/), rejects bad tokens early, rate-limits by client, and relays the token downstream (or exchanges it for a…
  • How do you use SpEL for fine-grained access control? — SpEL expressions in @PreAuthorize/@PostAuthorize can combine authorities, method arguments (#id), return values (returnObject), the authentication object, and custom bean methods (@beanName.method(...)) — `@PreAuthorize("hasAuthority('orders:write') and…
  • There are ADMIN and USER roles, each with different endpoints. How do you configure access control? — Put URL rules in the SecurityFilterChain, ordered from most specific to most general, and deny by default — @Bean SecurityFilterChain api(HttpSecurity http) throws Exception {
  • What is digest authentication? — An old HTTP authentication scheme (RFC 7616). Instead of sending the password, the client sends a hash of the username, password, a server nonce and the request details.

Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions — open the lesson

  • What's the best practice for storing passwords? — Never store passwords in plaintext, or reversibly. Store a hash from a slow, salted, adaptive algorithm: BCrypt (Spring's default), Argon2id, scrypt or PBKDF2.
  • What does the Spring Security filter chain do, and how do you add a custom filter? — Every request passes through DelegatingFilterProxy → FilterChainProxy, which picks the first matching SecurityFilterChain, and runs its ordered filters. Among them: SecurityContextHolderFilter; CSRF; logout; the authentication filters (form, Basic, bearer token); …
  • How does Spring Security handle session management, and how do you control concurrent sessions? — Creation policy: ALWAYS, IF_REQUIRED (the default), NEVER, or STATELESS (for token APIs); Session-fixation protection: the session ID changes at login (changeSessionId, the default); Invalid or expired session handling, and timeouts; Concurrency control:…
  • Users are unexpectedly denied access to a resource they should reach. How do you debug it? — Work through it systematically: Turn on security logging: logging.level.org.springframework.security=TRACE. It logs which SecurityFilterChain matched, each filter, and why authorisation failed; Check authentication. Is it a 401 (not authenticated: expired token, missing…
  • How do you implement dynamic access-control policies? — When the rules live in data (a permissions table, per-tenant policies, or feature entitlements) rather than code: Implement a custom AuthorizationManager<RequestAuthorizationContext> for URL rules, or AuthorizationManager<MethodInvocation> for methods, which loads the…
  • How do you test security configurations? — With spring-security-test, combined with @WebMvcTest or @SpringBootTest: @WithMockUser(roles = "ADMIN"), @WithAnonymousUser and @WithUserDetails, for method or MVC tests; MockMvc request post-processors: .with(jwt().authorities(...)), .with(csrf()),…
  • What is salting, and how is it used in Spring Security? — A salt is a random value generated per password, and combined with it before hashing. Identical passwords then get different hashes, and precomputed rainbow tables become useless.
  • How can you use SpEL for fine-grained access control? (Asked again: a real example) — Here's a realistic banking rule, with a limit that depends on the caller's role — @PreAuthorize(""" hasRole('TELLER') and #amount <= 50000
  • What are AuthenticationManager and ProviderManager? — AuthenticationManager is the interface with a single method, authenticate(Authentication), which returns a fully authenticated token or throws AuthenticationException. ProviderManager is its main implementation. It holds a list of AuthenticationProviders, and asks…
  • How do you redirect unauthorised users to a custom "access denied" page? — Configure the ExceptionTranslationFilter handlers: For authenticated users without permission, set an AccessDeniedHandler, or simply accessDeniedPage("/access-denied"); For unauthenticated users, set an AuthenticationEntryPoint. It redirects to the login page for web…

Follow-up questions this topic invites — and their answers

Q: How should I use this list in the last week before an interview? A: Do one pass per day. Cover the answer text, say your answer out loud, then check it. Mark every question you could not answer crisply, and spend your study time only on the marked ones by opening the linked full answer. By the third pass the marked list should be short.

Q: The interviewer asks one of these basics — should I give only the one-liner? A: Lead with the one-liner, then add one concrete detail or example from your own work. At this level the follow-up usually probes the mechanism behind the basic answer, so be ready to go one layer deeper using the key points in the full lesson.

Q: Some answers here were corrected compared with common prep sheets — why? A: Several widely shared answers are outdated or wrong (for example, Java version details, removed Spring APIs, or SQL queries that miss edge cases). The full lessons call these out under "Common trap" — reading those is the fastest way to stand out from candidates who memorised the same sheets.

Previous

Revise: Multithreading & Concurrency (2–5 Years Tier)

Next

Revise: Kafka, Git/Maven/Gradle, Deployment & Testing (2–5 Years Tier)

AI Tutor

Lesson: Revise: Spring Framework, Spring Boot & Security (2–5 Years Tier)

Quick actions

AI responses can be inaccurate. Verify critical information.