82 Spring Interview Questions and Answers (2026)

Blog / 82 Spring Interview Questions and Answers (2026)
Spring framework interview questions and answers

Spring still runs the backbone of enterprise Java, and as more teams ship AI/ML-backed APIs on the JVM, interviewers expect real fluency, not buzzword recall. They'll dig into how auto-configuration works, why @Transactional behaves the way it does, and what actually happens at runtime. Walk in shaky on those and the offer goes to someone who isn't.

This guide gives you 82 questions with tight, interview-ready answers and code where it helps. It's structured Junior to Mid to Senior, so you build from IoC and bean lifecycle up to Security, Spring Cloud, and reactive. Work through it and you'll have an answer ready before they finish asking.

Q1.
Explain the role of the @SpringBootApplication annotation and the three annotations it encapsulates.

Junior

@SpringBootApplication is a convenience meta-annotation placed on the main class that combines the three annotations needed to bootstrap a typical Spring Boot app.

  • @SpringBootConfiguration: A specialization of @Configuration: marks the class as a source of bean definitions.

  • @EnableAutoConfiguration: Activates Spring Boot's auto-configuration, registering beans conditionally based on the classpath.

  • @ComponentScan:

    • Scans the package of the main class and its sub-packages for @Component-style beans.

    • Reason to place the main class in a root package: scanning starts from there.

  • You can override its defaults: e.g. @SpringBootApplication(scanBasePackages=..., exclude=...) to tune scanning or exclude an auto-config.

Q2.
Explain the concept of Inversion of Control and how Dependency Injection implements it.

Junior

Inversion of Control (IoC) means an object no longer creates or looks up its own dependencies; control of that wiring is inverted to the framework. Dependency Injection (DI) is the concrete technique Spring uses to implement IoC: the container supplies a bean's collaborators from outside.

  • IoC: the principle:

    • Instead of new-ing dependencies, a class declares what it needs and the container provides it.

    • Benefits: loose coupling, easier testing (inject mocks), and centralized configuration.

  • DI: the implementation: The Spring ApplicationContext reads bean definitions, builds the object graph, and resolves dependencies.

  • Forms of injection:

    1. Constructor injection: preferred, enables immutability and required dependencies.

    2. Setter injection: for optional dependencies.

    3. Field injection (@Autowired on a field): concise but harder to test.

java

@Service public class OrderService { private final PaymentGateway gateway; // Container injects the dependency; OrderService never creates it public OrderService(PaymentGateway gateway) { this.gateway = gateway; } }

Q3.
What is the difference between Spring and Spring Boot, and what specific problems does Boot solve?

Junior

Spring is the core framework (IoC container, DI, MVC, data, etc.); Spring Boot is an opinionated layer on top that removes boilerplate configuration and makes Spring apps quick to start and run standalone.

  • Spring (the framework): Powerful but historically required heavy manual configuration (XML or extensive Java config) and external server setup.

  • Problems Boot solves:

    • Configuration overhead: auto-configuration wires sensible defaults based on the classpath.

    • Dependency management: starter POMs bundle compatible libraries so you don't curate versions.

    • Deployment: an embedded server (Tomcat/Jetty) lets you run a fat JAR with java -jar, no external app server.

    • Production readiness: Actuator adds health, metrics, and monitoring endpoints out of the box.

  • Key point: Boot doesn't replace Spring: it configures and packages it. Convention over configuration.

Q4.
What is the difference between @Bean and @Component, and when would you prefer one over the other?

Junior

Both register beans, but they apply at different levels: @Component is a class-level annotation discovered by component scanning, while @Bean is a method-level annotation inside a configuration class where you explicitly construct the bean.

  • @Component: auto-detection:

    • Put on your own classes; Spring finds and instantiates them via @ComponentScan.

    • Spring controls construction, so you can't customize instantiation logic much.

  • @Bean: explicit definition:

    • You write the method body, giving full control over how the object is built and configured.

    • Essential for third-party classes you can't annotate (e.g. a library's RestTemplate or DataSource).

  • When to prefer each:

    • Your own application class: @Component (less boilerplate).

    • Third-party class or conditional/customized construction: @Bean.

Q5.
How does @ComponentScan work, and how does Spring discover and register beans?

Junior

@ComponentScan tells Spring which packages to scan for stereotype-annotated classes, instantiate them as beans, and register their definitions in the ApplicationContext.

  • What it scans for:

    • Classes annotated with @Component or its specializations (@Service, @Repository, @Controller).

    • Default base package is the package of the @ComponentScan (or @SpringBootApplication) class and below.

  • How discovery works:

    1. A classpath scanner finds candidate components without loading every class fully (uses ASM bytecode reading).

    2. Each candidate becomes a BeanDefinition (metadata: class, scope, lazy, dependencies).

    3. The container instantiates beans, resolves dependencies, and applies post-processors.

  • Filtering: includeFilters and excludeFilters let you narrow scanning by annotation, type, or regex.

  • @Bean vs scanning: @ComponentScan registers beans by discovering classes; @Bean methods in a @Configuration register them explicitly.

Q6.
What is the purpose of the @Qualifier annotation, and how does it resolve ambiguity during autowiring?

Junior

@Qualifier tells Spring exactly which bean to inject when more than one candidate matches the required type, resolving the NoUniqueBeanDefinitionException by naming the target.

  • The problem it solves: Autowiring by type is ambiguous when two beans implement the same interface; Spring needs a tiebreaker.

  • How it resolves:

    • The value matches a bean name (or a custom qualifier value), narrowing candidates to exactly one.

    • Applied at the field, constructor parameter, or setter parameter.

  • Beyond bean names: You can define a custom qualifier annotation (meta-annotated with @Qualifier) for type-safe, descriptive matching instead of string names.

  • Interaction with @Primary: @Qualifier is explicit and overrides any @Primary default.

java

@Autowired public NotificationService(@Qualifier("smsSender") MessageSender sender) { this.sender = sender; // picks the bean named "smsSender" }

Q7.
What is the purpose of Spring Boot Starters and how do they simplify dependency management compared to traditional Spring?

Junior

Spring Boot Starters are curated, opinionated dependency bundles: adding one starter pulls in a coherent, version-aligned set of libraries for a capability, so you stop hand-picking and version-matching individual jars.

  • What a starter is: A thin POM with no code that transitively declares everything needed, e.g. spring-boot-starter-web brings Spring MVC, Jackson, and embedded Tomcat.

  • Version management:

    • The parent (spring-boot-starter-parent) or the BOM (spring-boot-dependencies) pins compatible versions, so you usually omit <version> entirely.

    • This eliminates the version-conflict guesswork common in traditional Spring projects.

  • Contrast with traditional Spring:

    • Before, you manually added spring-webmvc, a JSON library, a servlet container, and reconciled versions yourself.

    • Starters also trigger auto-configuration: their presence on the classpath is what conditional auto-config keys off of.

Q8.
What is the difference between @Controller and @RestController?

Junior

@Controller is the classic MVC controller that returns view names to be resolved into HTML, while @RestController is a convenience that writes return values directly to the response body as JSON/XML.

  • @RestController = @Controller + @ResponseBody: The combined annotation applies @ResponseBody to every method, so you don't repeat it.

  • @Controller return values:

    • A returned String is treated as a view name and passed to a ViewResolver (Thymeleaf, JSP).

    • To return data instead, you must add @ResponseBody on the method.

  • @RestController return values: Objects are serialized by an HttpMessageConverter (e.g. Jackson) into the response body.

  • Rule of thumb: Use @Controller for server-rendered pages, @RestController for REST APIs.

Q9.
Explain the difference between @PathVariable and @RequestParam.

Junior

Both bind request data to method parameters, but @PathVariable extracts a value embedded in the URL path, while @RequestParam extracts a query-string parameter (or form field).

  • @PathVariable:

    • Reads a URI template segment: /users/{id} maps id to the parameter.

    • Used to identify a resource; part of the path itself.

  • @RequestParam:

    • Reads ?key=value from the query string: /users?role=admin.

    • Good for filtering, sorting, pagination, and optional inputs; supports required and defaultValue.

  • Rule of thumb: path identifies the resource; query refines or filters it.

java

@GetMapping("/users/{id}/orders") public List<Order> getOrders( @PathVariable Long id, @RequestParam(defaultValue = "PENDING") String status) { return service.find(id, status); }

Q10.
What is the difference between @RequestBody, @ResponseBody, and returning a ResponseEntity from a controller method?

Junior

They sit at different points of the request: @RequestBody deserializes the incoming HTTP body into an object, @ResponseBody serializes the returned object into the response body, and ResponseEntity wraps that body together with status code and headers.

  • @RequestBody: Inbound: an HttpMessageConverter (usually Jackson) converts JSON/XML into a Java object parameter.

  • @ResponseBody:

    • Outbound: the return value is written directly to the body instead of being resolved as a view name.

    • Implied by @RestController, so you rarely write it explicitly.

  • ResponseEntity:

    • Full control: set the status (201 Created, 404), custom headers, and the body.

    • Use it when status/headers vary; otherwise returning the object plus @ResponseBody defaults to 200 OK.

java

@PostMapping("/users") public ResponseEntity<User> create(@RequestBody UserDto dto) { User saved = service.save(dto); return ResponseEntity.status(HttpStatus.CREATED).body(saved); }

Q11.
How do you implement pagination and sorting in Spring Data using Pageable and Page?

Junior

You accept a Pageable parameter (page number, size, and sort) on a repository method and return a Page<T>; Spring Data applies the limit/offset and runs a count query so you get both the data and total metadata.

  • Pageable:

    • Carries page index (0-based), page size, and Sort; build it with PageRequest.of(page, size, sort).

    • In Spring MVC controllers it can be resolved automatically from request params (?page=0&size=20&sort=name,desc).

  • Return types:

    • Page<T>: includes content plus total count via getTotalElements() and getTotalPages() (runs an extra count query).

    • Slice<T>: only knows if there is a next page (no count query), cheaper for infinite scroll.

    • List<T>: just the page content, no metadata.

  • Sorting: Pass Sort.by("field").descending() alone, or embed it in the Pageable.

  • Caveat: Paging plus a fetched collection in one query can break pagination (in-memory paging); use Slice or fetch in a second query.

java

Page<User> findByActiveTrue(Pageable pageable); // usage Pageable pageable = PageRequest.of(0, 20, Sort.by("lastName").ascending()); Page<User> page = repo.findByActiveTrue(pageable); long total = page.getTotalElements(); List<User> users = page.getContent();

Q12.
Explain the difference between application.properties and application.yml. When might you prefer one over the other?

Junior

Both define the same Spring configuration; .properties is flat key=value, while .yml is hierarchical YAML that is more readable for nested and structured config.

  • application.properties: Flat keys (spring.datasource.url=...); simple, no indentation pitfalls.

  • application.yml:

    • Nested structure, less repetition, supports lists naturally, and multiple profiles in one file via --- separators.

    • Whitespace-sensitive: bad indentation causes subtle errors.

  • When to prefer which:

    • Prefer YAML for large, hierarchical, multi-profile config; prefer properties for small/simple setups or to avoid YAML parsing quirks.

    • If both exist, properties wins over yml for the same key.

Q13.
What are @PostConstruct and @PreDestroy used for in the bean lifecycle?

Junior

They are JSR-250 lifecycle annotations: @PostConstruct marks a method to run once after dependencies are injected, and @PreDestroy marks a method to run before the bean is destroyed.

  • @PostConstruct:

    • Runs after construction and injection, so dependencies are available: good for initialization, caches, validation.

    • Don't put init logic in the constructor where dependencies aren't yet wired.

  • @PreDestroy:

    • Runs during graceful shutdown: release resources, close pools/connections.

    • Only fires for singletons (container doesn't track prototype destruction).

  • Why prefer them: Annotation-based and decoupled from Spring interfaces like InitializingBean/DisposableBean.

Q14.
How do you schedule recurring tasks in Spring using @Scheduled, and what does @EnableScheduling do?

Junior

@Scheduled marks a method to be invoked automatically on a timer, and @EnableScheduling activates the background scheduler that scans for and runs those methods. The annotated method must have no arguments and return void.

  • @EnableScheduling turns the feature on: Registers a ScheduledAnnotationBeanPostProcessor that finds @Scheduled methods and registers them with a TaskScheduler.

  • Triggers on @Scheduled:

    • fixedRate: starts each run a fixed interval apart, regardless of how long the previous run took.

    • fixedDelay: waits a fixed gap after the previous run finishes before starting the next.

    • cron: a cron expression for calendar-based schedules (e.g. 0 0 * * * * hourly).

    • initialDelay: delays the first execution.

  • Single thread by default: All scheduled tasks share one thread, so a slow task delays others; supply a pooled TaskScheduler or use @Async for concurrency.

java

@Component class Jobs { @Scheduled(fixedDelay = 5000) public void poll() { /* runs 5s after each completion */ } @Scheduled(cron = "0 0 2 * * *") // 2 AM daily public void nightlyCleanup() { /* ... */ } }

Q15.
What is the difference between Authentication and Authorization in Spring Security?

Junior

Authentication answers "who are you?" by verifying identity, while authorization answers "what are you allowed to do?" by checking permissions. Authentication always happens first; authorization uses its result.

  • Authentication:

    • Validates credentials (password, token, certificate) via an AuthenticationManager / AuthenticationProvider.

    • Produces an authenticated Authentication object containing the principal and granted authorities.

  • Authorization:

    • Decides access by examining the principal's authorities/roles against rules.

    • Configured via URL rules (authorizeHttpRequests) or method security (@PreAuthorize, @Secured).

  • Failure responses differ: Failed authentication typically yields 401 Unauthorized; failed authorization yields 403 Forbidden.

  • Both read from the same shared SecurityContext: authentication writes it, authorization reads it.

Q16.
What is the difference between BeanFactory and ApplicationContext, and when would you choose one over the other?

Mid

Both are Spring IoC containers, but ApplicationContext is a superset of BeanFactory that adds enterprise features; in practice you almost always use ApplicationContext.

  • BeanFactory: the basic container:

    • Provides DI and bean lifecycle, but lazily instantiates beans on demand.

    • Minimal footprint: historically suited to very memory-constrained environments.

  • ApplicationContext: the full-featured container:

    • Eagerly pre-instantiates singletons at startup, so misconfiguration fails fast.

    • Adds internationalization (MessageSource), event publishing (ApplicationEvent), automatic BeanPostProcessor/BeanFactoryPostProcessor registration, and AOP integration.

  • Which to choose:

    • Use ApplicationContext for essentially all applications (Spring Boot uses it by default).

    • BeanFactory is rarely chosen deliberately today; it's mostly an internal abstraction.

Q17.
What is the difference between @Component, @Service, @Repository, and @Controller, and are they technically different at runtime?

Mid

All four are stereotype annotations that mark a class as a Spring-managed bean; @Service, @Repository, and @Controller are specializations of @Component that add semantic meaning and, in some cases, extra behavior.

  • @Component: the generic stereotype: For any Spring-managed bean with no specialized role.

  • @Service: business/service layer: Purely semantic today: no added runtime behavior, just intent.

  • @Repository: persistence layer: Adds real behavior: enables exception translation, converting native persistence exceptions into Spring's DataAccessException hierarchy.

  • @Controller: web layer: Recognized by Spring MVC for request mapping; @RestController combines it with @ResponseBody.

  • Are they different at runtime?:

    • For component scanning they're identical (all detected as beans).

    • The differences are semantic clarity plus the specific extra processing @Repository and @Controller trigger.

Q18.
Why is Constructor Injection generally preferred over Field Injection, and what are the tradeoffs regarding testability and immutability?

Mid

Constructor injection is preferred because it makes dependencies explicit and mandatory, allows fields to be final (immutable), and keeps objects testable without a Spring container.

  • Immutability: Dependencies can be final, set once at construction and never reassigned, which is thread-safe and clearer.

  • Mandatory and fully-initialized objects: You cannot create the object without its required collaborators, so no half-built bean with null fields.

  • Testability: In a unit test you just call new Service(mockRepo); with field injection you need reflection or a container to set privates.

  • Reveals design smells: A long constructor signals too many dependencies, hinting the class violates single responsibility.

  • Tradeoffs:

    • Field injection (@Autowired on a field) is terse but hides dependencies and resists immutability.

    • Constructor injection can expose circular dependencies (often a good thing, since it forces a fix).

java

@Service class OrderService { private final OrderRepository repo; // single constructor: @Autowired is optional OrderService(OrderRepository repo) { this.repo = repo; } }

Q19.
What are the different bean scopes in Spring, and when would you use Prototype over Singleton?

Mid

Bean scope defines a bean's lifecycle and how many instances the container manages. The default is singleton (one shared instance); use prototype when you need a fresh, independent instance on every injection or lookup.

  • singleton: One instance per container, created eagerly at startup and shared. Default and ideal for stateless services.

  • prototype: A new instance every time the bean is requested. Spring does not manage its full lifecycle (no destroy callback).

  • Web scopes (need a web context):

    • request: one instance per HTTP request.

    • session: one per HTTP session.

    • application / websocket: per ServletContext / per WebSocket session.

  • When prototype over singleton: The bean holds per-use mutable state that must not be shared (e.g. a stateful builder or a non-thread-safe helper).

Q20.
Explain the difference between @Primary and @Qualifier when resolving ambiguous dependencies.

Mid

Both resolve ambiguity when multiple beans match a type, but @Primary sets a default winner at the bean-definition side, while @Qualifier selects a specific bean by name at the injection point.

  • @Primary:

    • Marks one candidate as the default choice when no qualifier is given.

    • Declared on the bean (or @Bean method), so it applies globally.

  • @Qualifier:

    • Names the exact bean wanted at the injection site, overriding @Primary.

    • Fine-grained: different injection points can pick different beans.

  • Precedence: @Qualifier wins over @Primary because explicit selection beats a default.

  • Rule of thumb: Use @Primary for the one usual default; use @Qualifier when a specific consumer needs a non-default bean.

java

@Bean @Primary DataSource primaryDs() { ... } @Bean @Qualifier("reporting") DataSource reportingDs() { ... } @Autowired ReportService(@Qualifier("reporting") DataSource ds) { ... } // picks reporting

Q21.
When would you use a Prototype scope bean instead of the default Singleton scope, and what are the risks of injecting a Prototype bean into a Singleton bean?

Mid

Use a prototype bean when each user needs its own stateful, non-shareable instance. The risk with injecting one into a singleton is that the prototype is resolved only once (at singleton creation), so the singleton keeps reusing the same instance, defeating the prototype semantics.

  • When to use prototype:

    • Beans carrying mutable per-operation state (builders, accumulators, non-thread-safe objects).

    • When sharing one instance would cause concurrency or stale-state bugs.

  • The injection trap: A singleton is wired once at startup, so its prototype dependency is injected once and frozen, you do NOT get a new one per call.

  • Fixes to get a fresh instance per use:

    • Inject ObjectProvider<T> (or Provider<T>) and call getObject() each time.

    • Use method injection via @Lookup.

    • Use a scoped proxy (proxyMode = TARGET_CLASS) so each access resolves a new target.

  • Also remember: Spring does not call destroy callbacks on prototypes; cleanup is the caller's responsibility.

Q22.
What does @Lazy do, and when would you make a bean lazily initialized?

Mid

@Lazy defers a bean's creation until it is first actually needed instead of at container startup. You use it to speed up startup, break dependency cycles, or avoid building expensive beans that may never be used.

  • Default vs lazy: Singletons are eagerly instantiated at startup by default; @Lazy delays this to first access.

  • How injection works: When a lazy bean is injected into an eager one, Spring injects a proxy; the real bean is created on first method call.

  • When to use it:

    • Expensive-to-build beans (heavy connections, large caches) used only in rare code paths.

    • To break a circular dependency by lazily injecting one side as a proxy.

    • To reduce application startup time.

  • Tradeoffs:

    • Errors in bean creation surface later (at first use) instead of at startup, hiding misconfiguration.

    • Adds a small first-access latency and proxy overhead.

Q23.
What is the purpose of Spring Boot Actuator, and which endpoints are most critical for production monitoring?

Mid

Spring Boot Actuator exposes production-ready operational endpoints (health, metrics, info, environment) over HTTP or JMX so you can monitor and manage a running application without writing custom infrastructure.

  • Purpose:

    • Adds introspection and management endpoints out of the box once you include spring-boot-starter-actuator.

    • Integrates with monitoring systems via Micrometer, which acts as a vendor-neutral metrics facade (Prometheus, Datadog, etc.).

  • Most critical endpoints:

    • /actuator/health: liveness/readiness status, often wired into Kubernetes probes and load balancers.

    • /actuator/metrics and /actuator/prometheus: JVM, CPU, latency, and custom metrics for dashboards and alerts.

    • /actuator/info: build/version metadata for deployment verification.

    • /actuator/loggers: view and change log levels at runtime without redeploying.

  • Security note: Only health and info are exposed over HTTP by default; others must be opted in via management.endpoints.web.exposure.include and protected, since they can leak sensitive data (env, heapdump).

Q24.
What are the major differences between Spring Boot 2.x and Spring Boot 3.x?

Mid

Spring Boot 3.x is a major modernization built on Spring Framework 6: it raises the baseline to Java 17, moves from Java EE to Jakarta EE, and adds first-class native-image and observability support.

  • Java baseline: 3.x requires Java 17+; 2.x supported Java 8+.

  • Jakarta EE namespace: All javax.* imports become jakarta.* (servlet, persistence, validation): the biggest migration pain point.

  • Native images: Built-in GraalVM AOT support for fast-starting, low-memory native executables.

  • Observability: New Micrometer Observation API unifies metrics and distributed tracing; tracing moves off Spring Cloud Sleuth.

  • Other: Updated third-party baselines (Hibernate 6, Jakarta-based dependencies) and removal of long-deprecated APIs.

Q25.
Explain the Spring Boot startup process. What happens when you run a @SpringBootApplication?

Mid

Running a @SpringBootApplication calls SpringApplication.run(), which bootstraps the application: it creates and configures an ApplicationContext, performs component scanning and auto-configuration, then starts the embedded server.

  • The annotation is a meta-annotation: Combines @Configuration, @ComponentScan, and @EnableAutoConfiguration.

  • Startup sequence:

    1. Detect the application type (servlet, reactive, none) from the classpath.

    2. Create the matching ApplicationContext and load ApplicationContextInitializers and listeners.

    3. Prepare the Environment (properties, profiles, command-line args).

    4. Component-scan for beans and apply auto-configuration via @EnableAutoConfiguration.

    5. Instantiate the bean definitions (the refresh phase), running constructors and post-processors.

    6. Start the embedded server (e.g. Tomcat) and fire ApplicationRunner/CommandLineRunner callbacks.

  • Auto-configuration source: Candidate configs are listed in META-INF/spring/...AutoConfiguration.imports and applied conditionally based on classpath and properties.

Q26.
Explain the request lifecycle in Spring MVC. What is the role of the DispatcherServlet?

Mid

Spring MVC follows the front-controller pattern: a single DispatcherServlet receives every request, delegates to the right handler, and coordinates the response. It is the central orchestrator of the request lifecycle.

  • Lifecycle steps:

    1. Request hits the DispatcherServlet (mapped to a URL pattern).

    2. It consults HandlerMapping to find the controller method for the URL.

    3. A HandlerAdapter invokes that method, binding parameters and running any interceptors.

    4. The controller returns a ModelAndView or a body object.

    5. For views, a ViewResolver resolves the logical name to a View that renders output; for @ResponseBody, an HttpMessageConverter serializes it.

    6. The response is returned to the client.

  • Role of the DispatcherServlet:

    • It owns the workflow but delegates each concern to pluggable strategy beans, keeping the framework extensible.

    • It also routes exceptions to HandlerExceptionResolvers for centralized error handling.

Q27.
Explain Content Negotiation in Spring. How does the framework decide whether to return JSON or XML?

Mid

Content negotiation is how Spring picks the response representation (JSON, XML, etc.) by matching what the client asks for against what the server can produce, then selecting the appropriate HttpMessageConverter.

  • How the format is determined (priority order):

    1. The Accept header is the default and preferred signal (e.g. Accept: application/xml).

    2. Optionally a URL path extension or a query parameter (?format=xml), if enabled.

  • Converter selection:

    • Spring matches the requested media type to a registered converter (Jackson for JSON, Jackson-XML/JAXB for XML).

    • A converter is only available if its library is on the classpath, so JSON works out of the box but XML needs an XML dependency.

  • Constraining at the endpoint: @RequestMapping(produces = ...) limits which media types a handler will return.

  • Configuration: Customize via ContentNegotiationConfigurer (e.g. favor a parameter, set a default media type).

Q28.
Explain the difference between a Filter and an Interceptor in the context of a Spring web application.

Mid

Both intercept requests, but a Filter belongs to the Servlet container (works on raw ServletRequest/ServletResponse), while an HandlerInterceptor belongs to Spring MVC and is aware of the handler (controller method) being invoked.

  • Filter (Servlet spec):

    • Defined by the container, runs before the DispatcherServlet; sees every request, including static resources.

    • Operates on the low-level request/response and the FilterChain; no knowledge of which controller will handle it.

    • Good for cross-cutting servlet concerns: logging, compression, security (Spring Security is filter-based), encoding.

  • Interceptor (Spring MVC):

    • Managed by Spring, runs inside the DispatcherServlet lifecycle and knows the target handler.

    • Three hooks: preHandle(), postHandle() (before view render), and afterCompletion().

    • Good for MVC-aware concerns: handler-specific auth checks, adding model attributes, timing controller execution.

  • Ordering: filters wrap the entire request, so they run before and after interceptors.

Q29.
How do you handle CORS in a Spring Boot application?

Mid

CORS lets the browser allow cross-origin calls; in Spring Boot you configure which origins, methods, and headers are permitted, either narrowly per-controller or globally.

  • Per-handler with @CrossOrigin: Annotate a controller or method to allow specific origins for just those endpoints.

  • Global via WebMvcConfigurer: Override addCorsMappings() to set allowed origins/methods/headers for path patterns in one place.

  • With Spring Security: Security filters run before MVC, so register a CorsConfigurationSource bean and enable http.cors() or the MVC config is bypassed.

  • Note: the browser enforces CORS via a preflight OPTIONS request; avoid combining allowedOrigins("*") with allowCredentials(true) (use allowedOriginPatterns instead).

java

@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("https://app.example.com") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowCredentials(true); } }

Q30.
What are the core concepts of AOP: Aspect, Advice, Pointcut, and JoinPoint?

Mid

AOP modularizes cross-cutting concerns; its core vocabulary describes what behavior to add, when to add it, and where. An Aspect bundles Advice (the action) with a Pointcut (where it applies), and each matched point of execution is a JoinPoint.

  • Aspect: A module encapsulating a cross-cutting concern (logging, security, transactions); marked @Aspect.

  • JoinPoint: A point during execution where advice could run; in Spring AOP this is always a method execution.

  • Pointcut: An expression that selects which join points match (e.g. execution(* com.app.service.*.*(..))).

  • Advice: The actual code that runs at a matched join point, plus its timing (@Before, @After, @Around).

  • Mnemonic: Pointcut = where, Advice = what/when, JoinPoint = the specific spot hit, Aspect = the package of all of it.

Q31.
Explain the different types of Advice (Before, After, Around, AfterReturning, AfterThrowing). When would you use @Around?

Mid

Advice types differ by when they run relative to the join point. @Around is the most powerful because it surrounds the call and controls whether and how it proceeds.

  • @Before: Runs before the method; cannot stop it (unless it throws). Good for validation, logging entry.

  • @AfterReturning: Runs only on successful return; can inspect the returned value.

  • @AfterThrowing: Runs only if the method throws; useful for error logging or translation.

  • @After: A finally block: runs on both success and failure (cleanup).

  • @Around:

    • Wraps the call via ProceedingJoinPoint; you decide whether to call proceed(), can modify args/return value, and handle exceptions.

    • Use when you need timing/metrics, caching, retries, or to short-circuit the call entirely.

java

@Around("execution(* com.app.service.*.*(..))") public Object time(ProceedingJoinPoint pjp) throws Throwable { long start = System.nanoTime(); try { return pjp.proceed(); // call the target } finally { log.info("{} took {}ns", pjp.getSignature(), System.nanoTime() - start); } }

Q32.
When would you use AOP instead of standard OOP?

Mid

Use AOP for cross-cutting concerns that would otherwise be scattered and duplicated across many unrelated classes; use OOP for the core domain behavior that naturally belongs to an object. AOP complements OOP, it does not replace it.

  • Good fits for AOP:

    • Concerns that span layers: logging, transactions (@Transactional), security checks, caching, metrics, retries.

    • Behavior orthogonal to business logic, so embedding it would clutter every method.

  • Why not just OOP: Inheritance/composition can't cleanly factor a concern that cuts across many unrelated types; you'd repeat boilerplate (scattering) or tangle it into business code.

  • Stay with OOP when: The logic is part of the object's responsibility, or the indirection of proxies would obscure intent.

  • Tradeoff: AOP adds runtime indirection and can make flow harder to trace; reserve it for genuinely cross-cutting needs.

Q33.
What is the difference between CrudRepository, PagingAndSortingRepository, and JpaRepository?

Mid

They form a hierarchy of repository interfaces in Spring Data, each adding capabilities to the one below it: CrudRepository gives basic CRUD, PagingAndSortingRepository adds paging/sorting, and JpaRepository adds JPA-specific batch and flush operations.

  • CrudRepository<T, ID>: Core CRUD: save(), findById(), findAll(), delete(), count().

  • PagingAndSortingRepository<T, ID>: Extends CrudRepository and adds findAll(Pageable) and findAll(Sort) for page-based access and ordering.

  • JpaRepository<T, ID>: Extends both and adds JPA-specific methods: saveAndFlush(), flush(), deleteAllInBatch(), and returns List instead of Iterable.

  • Which to use: Pick the lowest interface that meets your needs; in practice JpaRepository is most common since it bundles everything, but exposing a narrower interface keeps the API intentional.

Q34.
How does Spring Data JPA generate queries from method names (Derived Queries)?

Mid

Spring Data parses the method name at startup, splits it into a subject (the action) and a predicate (the criteria), and builds the query from the property names and keywords it finds, validating them against your entity.

  • Name parsing: A prefix like findBy, readBy, countBy, existsBy, or deleteBy sets the action; the rest is the condition.

  • Property traversal: Each segment maps to an entity property; camelCase like findByUserAddressCity navigates nested associations (user.address.city).

  • Keywords build conditions: Operators come from keywords: And, Or, Between, LessThan, Like, In, IgnoreCase, and ordering via OrderBy...Desc.

  • Validated at startup: Unknown property names fail fast when the context loads, not at runtime.

  • Caveat: Long derived names get unreadable; switch to @Query once the criteria get complex.

java

// Generates: where last_name = ? and age > ? order by age desc List<User> findByLastNameAndAgeGreaterThanOrderByAgeDesc(String lastName, int age);

Q35.
What is the difference between save(), saveAndFlush(), and persist() in a Spring Data repository?

Mid

All three persist an entity, but they differ in when SQL hits the database and in semantics: save() inserts or updates and defers the flush, saveAndFlush() forces the SQL immediately, and persist() is the raw JPA insert-only operation underneath.

  • save():

    • Spring Data method: new entity is persisted, existing entity is merged.

    • SQL may be deferred until the transaction commits or the persistence context flushes.

  • saveAndFlush():

    • Same as save() then immediately calls flush(), so SQL runs now.

    • Useful when you need the DB state right away (trigger constraints, read your own write in the same transaction).

  • persist():

    • A raw EntityManager method, not on the repository interface: insert-only and throws if the entity already exists.

    • Returns void and makes the entity managed; save() internally uses persist() or merge() depending on whether it is new.

  • Key point on flush: Forcing flush adds DB round-trips and can hurt batching; only use saveAndFlush() when ordering or visibility truly requires it.

Q36.
What is the difference between JPQL and Native SQL queries in Spring Data JPA? When is one preferred over the other?

Mid

JPQL queries against your entity model (classes and fields) and is database-portable, while native SQL queries the actual tables/columns and is database-specific. Prefer JPQL for portability and entity mapping; reach for native SQL when you need vendor features or complex queries JPQL can't express.

  • JPQL:

    • Written against entity names and properties, e.g. select u from User u where u.name = :name.

    • Portable across databases; Hibernate translates it to dialect-specific SQL.

    • Returns mapped entities and respects the object model.

  • Native SQL:

    • Real SQL with nativeQuery = true; uses table and column names.

    • Access to vendor-specific syntax (window functions, hints, CTEs, full-text search).

    • Tied to the schema and database vendor, so less portable.

  • When to choose:

    • JPQL by default: portable, maintainable, entity-aware.

    • Native when you need performance tuning, DB-specific features, or bulk operations beyond JPQL's reach.

java

@Query("select u from User u where u.email = :email") User findByEmailJpql(@Param("email") String email); @Query(value = "SELECT * FROM users WHERE email = :email", nativeQuery = true) User findByEmailNative(@Param("email") String email);

Q37.
What are the tradeoffs of using Spring Data JPA vs JdbcTemplate?

Mid

Spring Data JPA gives you an ORM with automatic mapping, caching, and dirty-checking for productivity; JdbcTemplate gives you direct, predictable SQL with less abstraction and overhead. The choice is productivity and object model versus control and transparency.

  • Spring Data JPA strengths:

    • Less boilerplate: derived queries, automatic CRUD, entity mapping.

    • Persistence context features: caching, dirty checking, lazy loading, cascades.

  • Spring Data JPA costs:

    • Abstraction can hide expensive SQL (N+1 queries, surprise flushes).

    • Steeper learning curve and harder to reason about generated SQL.

  • JdbcTemplate strengths:

    • You write the SQL, so behavior and performance are explicit and tunable.

    • Lightweight, no persistence context overhead; great for reporting and bulk reads.

  • JdbcTemplate costs:

    • More boilerplate: manual RowMappers and SQL maintenance.

    • No automatic mapping, caching, or change tracking.

  • Pragmatic answer: They coexist well: JPA for domain CRUD, JdbcTemplate for hot-path or complex read queries where you want full control.

Q38.
What is the difference between JPA, Hibernate, and Spring Data JPA?

Mid

They sit at different levels: JPA is the specification, Hibernate is an implementation of that spec, and Spring Data JPA is a layer on top that removes repository boilerplate.

  • JPA (Jakarta Persistence API):

    • A specification: defines annotations (@Entity, @Id), the EntityManager API, and JPQL.

    • It is just interfaces and contracts, with no runtime engine of its own.

  • Hibernate:

    • The most popular JPA provider: actually implements the spec and does the ORM work (SQL generation, caching, dirty checking).

    • Also offers extra features beyond the spec (its own Session API, custom types).

  • Spring Data JPA:

    • A Spring abstraction over JPA: you declare repository interfaces and it generates implementations at runtime.

    • Adds derived queries, Pageable, and auditing; still delegates to a JPA provider like Hibernate underneath.

  • In short: Spring Data JPA uses JPA, which Hibernate implements: spec, provider, convenience layer.

Q39.
Explain the trade-offs between FetchType.LAZY and FetchType.EAGER.

Mid

They control when associated entities are loaded: LAZY defers loading until the association is first accessed, while EAGER loads it immediately with the owner. The tradeoff is avoiding wasted queries versus avoiding lazy-loading pitfalls.

  • FetchType.LAZY:

    • Loads the association only on access via a proxy; faster initial query and less memory.

    • Risk: LazyInitializationException if accessed after the persistence context (session) is closed.

    • Default for @OneToMany and @ManyToMany.

  • FetchType.EAGER:

    • Always loads the association, so data is available outside the session.

    • Risk: over-fetching and N+1 problems; can load large graphs you don't need.

    • Default for @ManyToOne and @OneToOne.

  • Best practice:

    • Prefer LAZY everywhere for control, then load what you need explicitly with a JOIN FETCH or an entity graph per use case.

    • This avoids both lazy exceptions and accidental over-fetching.

Q40.
What are Spring Profiles, and how do you use them to manage environment-specific configurations?

Mid

Spring Profiles let you register beans and configuration conditionally so a single artifact behaves differently per environment (dev, test, prod) by activating the right profile at runtime.

  • Mark beans/configs with @Profile:

    • A bean annotated with @Profile("dev") is created only when that profile is active.

    • Supports expressions like @Profile("!prod") for negation.

  • Profile-specific property files: Spring Boot loads application-{profile}.properties (or .yml) on top of the base application.properties.

  • Activating profiles: Via spring.profiles.active=prod, env var SPRING_PROFILES_ACTIVE, or --spring.profiles.active on the command line.

  • Benefit: One build artifact promoted across environments instead of rebuilding per environment.

Q41.
How do you manage externalized configuration in Spring Boot, and what is the priority order between properties, environment variables, and command-line arguments?

Mid

Spring Boot reads configuration from many ordered sources and merges them into a single Environment; higher-priority sources override lower ones, so the same property can be defaulted in a file and overridden at deploy time.

  • Common externalization sources: Property/YAML files, environment variables, JVM system properties, command-line args, and profile-specific files.

  • Priority order (highest wins, simplified):

    1. Command-line arguments (--server.port=9000).

    2. Java system properties (-Dserver.port).

    3. OS environment variables (SERVER_PORT, relaxed-binding name).

    4. Profile-specific files (application-{profile}.properties).

    5. The base application.properties/.yml.

  • Practical takeaway: Keep sane defaults in files; override secrets and per-environment values via env vars or command-line args without rebuilding.

Q42.
What is the difference between @Value and @ConfigurationProperties for binding external configuration?

Mid

Both bind external properties, but @Value injects a single property via SpEL into a field, while @ConfigurationProperties binds a whole group of related properties onto a typed POJO.

  • @Value:

    • Good for one-off values: @Value("${app.timeout:30}") with a default and SpEL support.

    • No relaxed binding, no nested objects, validation is awkward.

  • @ConfigurationProperties:

    • Binds a prefix to a structured class (nested objects, lists, maps).

    • Supports relaxed binding (app-name maps to appName) and JSR-303 validation with @Validated.

  • Rule of thumb: A single value: @Value. A cohesive group of settings: @ConfigurationProperties.

java

@ConfigurationProperties(prefix = "app") public class AppProps { private String name; private int timeout; // getters/setters -> binds app.name, app.timeout }

Q43.
What is the Spring application event mechanism, and how do you publish and listen for custom events with ApplicationEventPublisher and @EventListener?

Mid

Spring's event mechanism is an in-process publish/subscribe model: a publisher fires an event object and any registered listeners react, decoupling the sender from the receivers.

  • Define an event: Any POJO works (extending ApplicationEvent is optional since Spring 4.2).

  • Publish: Inject ApplicationEventPublisher and call publishEvent(...).

  • Listen:

    • Annotate a method with @EventListener; the parameter type selects which events it receives.

    • condition attribute filters via SpEL.

  • Sync by default:

    • Listeners run in the publisher's thread; add @Async for asynchronous handling.

    • @TransactionalEventListener can defer handling until commit.

java

// publish publisher.publishEvent(new OrderCreatedEvent(orderId)); // listen @EventListener void on(OrderCreatedEvent e) { // react to e.getOrderId() }

Q44.
How do you handle global exceptions in a Spring Boot REST API? Explain @ControllerAdvice and @ExceptionHandler.

Mid

You centralize error handling with a @RestControllerAdvice class containing @ExceptionHandler methods, so exceptions thrown anywhere in your controllers are translated into consistent HTTP responses without try/catch clutter in each handler.

  • @ControllerAdvice / @RestControllerAdvice:

    • A specialized component that applies cross-cutting advice (exception handling, model binding) to many controllers.

    • @RestControllerAdvice = @ControllerAdvice + @ResponseBody, so return values are serialized as the response body (JSON).

  • @ExceptionHandler:

    • Marks a method to handle a specific exception type; you map it to a status with @ResponseStatus or by returning a ResponseEntity.

    • Most specific match wins; you can build a uniform error-body DTO across the app.

  • Scope control: Limit which controllers are covered with @ControllerAdvice(basePackages=...) or by annotation/assignable type.

  • Standardized alternative: Extend ResponseEntityExceptionHandler to override Spring MVC's built-in exception handling, and prefer ProblemDetail (RFC 7807) for response bodies in newer Spring versions.

java

@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(EntityNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public ProblemDetail handleNotFound(EntityNotFoundException ex) { return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage()); } }

Q45.
What is the difference between @SpringBootTest and 'Test Slices' like @WebMvcTest or @DataJpaTest?

Mid

@SpringBootTest boots the full application context (everything), while test slices like @WebMvcTest and @DataJpaTest load only the beans for one layer, making them faster and more focused.

  • @SpringBootTest:

    • Loads the entire ApplicationContext, suited to integration tests spanning multiple layers.

    • Heavier and slower; pair with webEnvironment + TestRestTemplate / MockMvc for end-to-end checks.

  • Test slices in general: Auto-configure only the slice's relevant beans and disable the rest, giving fast, isolated tests.

  • @WebMvcTest: Loads the web layer (controllers, filters, MockMvc) but not services/repositories: mock collaborators with @MockBean.

  • @DataJpaTest: Loads JPA repositories and an embedded/in-memory DB, runs in a rolled-back transaction per test.

  • Rule of thumb: Prefer the narrowest slice that exercises the code under test; reserve @SpringBootTest for true cross-layer integration.

Q46.
When would you use @MockBean versus a standard Mockito @Mock?

Mid

Use @MockBean when a test loads a Spring context and you need to replace a real bean with a mock inside that context; use a plain Mockito @Mock for pure unit tests with no Spring container.

  • @Mock (Mockito):

    • Creates a standalone mock object, unaware of Spring; you wire it manually (constructor or @InjectMocks).

    • Fast, no context startup: ideal for isolated unit tests.

  • @MockBean (Spring Boot Test):

    • Adds or replaces a bean in the ApplicationContext with a Mockito mock, so context-managed components receive the mock when autowired.

    • Common in slice tests like @WebMvcTest to stub the service layer.

    • Replacing a bean dirties the context, which can trigger context reloads between tests (slower).

  • Rule of thumb: No Spring context, use @Mock; the bean must live in the loaded context, use @MockBean.

Q47.
How does @Transactional work, and what is Transaction Propagation (e.g., REQUIRED vs. REQUIRES_NEW)?

Mid

@Transactional makes Spring wrap the method in a proxy that begins a transaction, commits on success, and rolls back on runtime exceptions. Propagation tells that proxy how to behave when a transaction already exists: REQUIRED joins the caller's transaction, while REQUIRES_NEW suspends it and runs in an independent one.

  • How it works:

    • An AOP proxy delegates to a PlatformTransactionManager that opens, commits, or rolls back the transaction around the method.

    • Rolls back on unchecked exceptions by default; configure checked ones with rollbackFor.

  • REQUIRED (default): Joins an active transaction if present, otherwise creates one: everything commits or rolls back together.

  • REQUIRES_NEW:

    • Suspends any active transaction and runs in a brand-new, independent one that commits separately.

    • Useful for actions that must persist regardless of the outer transaction (e.g., audit logging).

  • Important nuance: A rollback in an inner REQUIRED segment marks the whole shared transaction rollback-only; a REQUIRES_NEW inner failure does not force the outer to roll back.

Q48.
Why would you use MockMvc instead of making actual HTTP calls in your controller tests?

Mid

MockMvc tests your controllers through Spring's MVC machinery in-process, without starting a real server or opening network sockets, so tests are faster, more reliable, and still exercise routing, serialization, validation, and exception handling.

  • No server, no network: Requests are dispatched directly to the DispatcherServlet in memory: no port binding, no flaky sockets, much faster.

  • Real MVC behavior: Still runs URL mapping, argument resolution, JSON (de)serialization, validation, filters, and @ControllerAdvice handlers.

  • Focused and expressive: Fluent assertions on status, headers, and body via andExpect(...); pairs well with @WebMvcTest plus mocked services.

  • When to use real HTTP instead: Use TestRestTemplate / WebTestClient with a running server (@SpringBootTest(webEnvironment=RANDOM_PORT)) for true end-to-end checks of the server stack.

java

mockMvc.perform(get("/users/1")) .andExpect(status().isOk()) .andExpect(jsonPath("$.name").value("Ada"));

Q49.
How does request body validation work in Spring? Explain @Valid, @Validated, and the BindingResult.

Mid

Bean Validation (JSR-380) integrates with Spring MVC so that annotating a controller argument with @Valid triggers constraint checks before your handler runs; if errors exist Spring either throws an exception or hands them to a BindingResult you inspect.

  • @Valid on a request body or model attribute:

    • Standard JSR-380 annotation that triggers validation of constraints like @NotNull, @Size, @Email on the target object.

    • Supports cascading: a nested object annotated with @Valid is validated too.

  • @Validated (Spring's variant):

    • Adds validation group support: @Validated(OnCreate.class) runs only constraints assigned to that group.

    • Placed at class level on a bean, it also enables method-level parameter validation via an AOP proxy.

  • BindingResult captures the errors:

    • Must be declared immediately after the validated argument; Spring populates it instead of throwing.

    • Without it, a failed @Valid on a body throws MethodArgumentNotValidException (usually mapped to a 400).

  • Centralize handling with @ControllerAdvice + @ExceptionHandler rather than checking BindingResult in every method.

java

@PostMapping("/users") public ResponseEntity<?> create(@Valid @RequestBody UserDto dto, BindingResult result) { if (result.hasErrors()) { return ResponseEntity.badRequest().body(result.getAllErrors()); } return ResponseEntity.ok(service.save(dto)); }

Q50.
What is the Spring caching abstraction, and how do @Cacheable, @CacheEvict, and @CachePut work?

Mid

Spring's caching abstraction is a declarative layer that wraps method calls with cache logic, letting you store and reuse results without coupling to a specific cache provider. You enable it with @EnableCaching and drive behavior with annotations backed by a CacheManager.

  • @Cacheable: read-through caching:

    • On the first call the method runs and its return value is stored under a key; subsequent calls with the same key skip the method and return the cached value.

    • Key is derived from method arguments (customizable via key SpEL) and a named value/cache.

  • @CachePut: always execute and update:

    • Runs the method every time and stores the result, keeping the cache in sync after an update.

    • Use on save/update methods so the cache reflects new state.

  • @CacheEvict: remove entries: Deletes a key (or all entries with allEntries = true) to invalidate stale data, typically on delete/update.

  • Provider-agnostic: The same annotations work over a ConcurrentMapCacheManager, Caffeine, Redis, etc.; you swap the CacheManager bean.

  • Pitfall: like other Spring AOP, caching works through proxies, so self-invocation within the same bean bypasses it.

java

@Cacheable(value = "users", key = "#id") public User findById(Long id) { return repo.findById(id).orElseThrow(); } @CachePut(value = "users", key = "#user.id") public User update(User user) { return repo.save(user); } @CacheEvict(value = "users", key = "#id") public void delete(Long id) { repo.deleteById(id); }

Q51.
How does @Async work in Spring, and what are the pitfalls such as self-invocation and thread pool configuration?

Mid

@Async tells Spring to run a method on a separate thread so the caller returns immediately. It works through an AOP proxy: a call to the annotated method is intercepted and submitted to a TaskExecutor, and must be enabled with @EnableAsync.

  • How it works: The proxy submits the invocation to an executor and returns void, a Future, or CompletableFuture so the caller isn't blocked.

  • Self-invocation pitfall: Calling an @Async method from another method in the same bean bypasses the proxy, so it runs synchronously. Call it from a different bean.

  • Thread pool configuration:

    • By default Spring may use a SimpleAsyncTaskExecutor that creates a new thread per task (no pooling): dangerous under load.

    • Define a ThreadPoolTaskExecutor bean with bounded core/max pool size and queue capacity, and reference it via @Async("executorName").

  • Other gotchas:

    • Exceptions from void async methods are swallowed unless you register an AsyncUncaughtExceptionHandler.

    • The SecurityContext and request-scoped beans aren't propagated to the new thread automatically.

java

@Configuration @EnableAsync class AsyncConfig { @Bean public Executor taskExecutor() { var ex = new ThreadPoolTaskExecutor(); ex.setCorePoolSize(4); ex.setMaxPoolSize(8); ex.setQueueCapacity(100); ex.initialize(); return ex; } } @Service class MailService { @Async public CompletableFuture<Void> send(String to) { /* ... */ return CompletableFuture.completedFuture(null); } }

Q52.
Explain the role of the SecurityContextHolder and how it stores user details during a request.

Mid

The SecurityContextHolder is the central holder that stores the current SecurityContext, which in turn holds the authenticated Authentication (the principal, credentials, and authorities) for the duration of a request.

  • Structure: SecurityContextHolder → SecurityContext → Authentication → principal (often a UserDetails) + GrantedAuthority set.

  • Thread-bound by default:

    • Uses a ThreadLocal strategy (MODE_THREADLOCAL), so the context is tied to the request thread.

    • Other strategies exist: MODE_INHERITABLETHREADLOCAL for child threads, MODE_GLOBAL for standalone apps.

  • Populated and cleared per request:

    • An authentication filter sets the Authentication after login; the chain clears the ThreadLocal at the end to avoid leaking identity across requests.

    • For session-based apps it's persisted in the HttpSession and restored on each request.

  • Access it anywhere via SecurityContextHolder.getContext().getAuthentication().

java

Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String username = auth.getName(); Collection<? extends GrantedAuthority> roles = auth.getAuthorities();

Q53.
How do you implement JWT-based authentication in Spring Security? Explain the conceptual flow from login to token validation.

Mid

JWT authentication makes the API stateless: the client logs in once, receives a signed token, and sends it on every subsequent request in an Authorization: Bearer header. A custom filter validates the token and populates the SecurityContext instead of relying on server-side sessions.

  • Login / token issuance:

    1. Client posts credentials to a login endpoint, which authenticates them via the AuthenticationManager.

    2. On success the server builds a JWT with claims (subject, roles, expiry) and signs it with a secret or private key.

    3. The signed token is returned to the client, which stores it.

  • Per-request validation:

    1. A custom filter (e.g. extending OncePerRequestFilter) reads the Bearer token.

    2. It verifies the signature and expiry; an invalid token is rejected.

    3. On success it builds an Authentication from the claims and sets it in the SecurityContextHolder.

  • Stateless by design:

    • Configure SessionCreationPolicy.STATELESS and register the JWT filter before UsernamePasswordAuthenticationFilter.

    • No server session: scaling is easy, but you can't trivially revoke a token before expiry.

  • Practical concerns:

    • Keep access tokens short-lived and use a refresh token for renewal.

    • For revocation, maintain a blacklist or rotate signing keys.

Q54.
What is CSRF, and why does Spring Security enable protection by default? When is it safe to disable it?

Mid

CSRF (Cross-Site Request Forgery) tricks an authenticated user's browser into submitting an unwanted state-changing request using their existing credentials (cookies). Spring Security enables protection by default because browser-managed credentials are sent automatically, so any authenticated session is vulnerable.

  • How the attack works: A malicious site issues a request to your app; the browser attaches the user's session cookie automatically, so the server thinks it's legitimate.

  • How Spring's protection works:

    • It requires a per-session CSRF token on unsafe methods (POST, PUT, DELETE) that an attacker's site cannot read or forge.

    • Safe methods (GET, HEAD, OPTIONS) are exempt because they shouldn't change state.

  • When it's safe to disable:

    • Stateless APIs using tokens (e.g. JWT in an Authorization header), since the credential isn't sent automatically by the browser.

    • Non-browser clients only (service-to-service). Keep it enabled for any cookie-based browser session.

Q55.
Explain the difference between hasRole() and hasAuthority() in Spring Security expressions.

Mid

Both check the user's granted authorities; the only difference is that hasRole() automatically prepends the ROLE_ prefix, while hasAuthority() matches the authority string exactly.

  • hasRole('ADMIN'): Actually checks for the authority ROLE_ADMIN; the prefix is added for you.

  • hasAuthority('ROLE_ADMIN'): Checks the literal string with no prefix added, so it's equivalent to hasRole('ADMIN').

  • Practical guidance:

    • Use hasRole() for coarse role checks and hasAuthority() for fine-grained permissions (e.g. document:read).

    • Ensure your GrantedAuthority values are stored consistently with the chosen prefix convention.

Q56.
What is the difference between @PreAuthorize and @Secured for method-level security?

Mid

Both secure methods, but @PreAuthorize evaluates rich SpEL expressions before the method runs, while @Secured only checks a static list of role names. @PreAuthorize is the modern, more powerful choice.

  • @Secured:

    • Takes plain role strings (@Secured("ROLE_ADMIN")); no expressions, no method-argument access.

    • Enabled with @EnableMethodSecurity(securedEnabled = true).

  • @PreAuthorize:

    • Uses SpEL, so you can combine checks and reference arguments and the principal: @PreAuthorize("hasRole('ADMIN') and #id == principal.id").

    • Enabled by default with @EnableMethodSecurity; complemented by @PostAuthorize for checks on the return value.

  • Bottom line: prefer @PreAuthorize for anything beyond a simple role match.

Q57.
Explain the difference between Method-level security with @PreAuthorize and URL-level security.

Mid

URL-level security guards request paths at the web/filter layer, while method-level security with @PreAuthorize guards individual business methods regardless of how they're reached. They work best together as defense in depth.

  • URL-level security:

    • Configured in the SecurityFilterChain via authorizeHttpRequests() with matchers like requestMatchers("/admin/**").hasRole("ADMIN").

    • Runs early as a filter, before the controller; coarse-grained, path-based.

  • Method-level security:

    • Annotations on service or controller methods enforced via AOP proxies, so the rule applies no matter the entry point.

    • Fine-grained: can reference method arguments and return values.

  • Why use both: URL rules block obvious unauthorized access cheaply; method rules protect the business logic even if it's invoked internally or through a new endpoint.

Q58.
How does JWT-based stateless authentication differ from session-based stateful authentication in Spring?

Mid

Session-based auth stores authentication state on the server and tracks the user via a session cookie; JWT-based auth is stateless, carrying the user's identity and claims inside a signed token the server verifies on each request.

  • Session-based (stateful):

    • Server keeps a session (in memory or a store); the client holds only a JSESSIONID cookie.

    • Easy to invalidate (drop the session) but needs sticky sessions or a shared store to scale horizontally.

  • JWT-based (stateless):

    • The signed token carries claims; the server validates the signature and expiry, storing nothing. Configure SessionCreationPolicy.STATELESS.

    • Scales cleanly across instances, but tokens are hard to revoke before expiry (need short lifetimes, refresh tokens, or a blocklist).

  • Trade-off summary: Sessions = simple revocation, server-side state; JWT = horizontal scalability, harder invalidation.

Q59.
What are the roles of UserDetailsService and PasswordEncoder in Spring Security authentication?

Mid

During authentication, UserDetailsService loads the user (and their stored hashed password and authorities) by username, and PasswordEncoder verifies the submitted raw password against that stored hash. Together they back the DaoAuthenticationProvider.

  • UserDetailsService:

    • A single method, loadUserByUsername(), returns a UserDetails (username, encoded password, authorities, account flags).

    • Throws UsernameNotFoundException if no such user; it's where you plug in your DB lookup.

  • PasswordEncoder:

    • Hashes passwords on registration and verifies via matches(raw, encoded); never stores or compares plaintext.

    • Use a strong adaptive algorithm: BCryptPasswordEncoder or the DelegatingPasswordEncoder (the default) which supports upgrading hash schemes.

  • Flow: The provider loads the user, then calls matches(); success yields an authenticated Authentication with the user's authorities.

Q60.
What is a Circuit Breaker (e.g., Resilience4j), and how does it prevent cascading failures in a microservices architecture?

Mid

A circuit breaker is a resilience pattern that monitors calls to a remote dependency and, once failures cross a threshold, "opens" to fail fast instead of waiting on a failing service. This stops one slow/broken service from exhausting resources and dragging down callers across the system.

  • The three states:

    1. CLOSED: calls pass through normally while failure rate is monitored.

    2. OPEN: after the threshold is breached, calls are rejected immediately (often returning a fallback) for a cooldown period.

    3. HALF_OPEN: a few trial calls are allowed; success closes the breaker, failure reopens it.

  • How it prevents cascading failures:

    • Failing fast frees threads and connection pools instead of blocking on timeouts, so the caller stays healthy.

    • A fallback (cached data, default, graceful error) keeps the user experience degraded-but-alive.

  • In Spring with Resilience4j:

    • Annotate with @CircuitBreaker(name="svc", fallbackMethod="fallback") and tune thresholds in config.

    • Often combined with retry, timeout, and bulkhead patterns for full resilience.

Q61.
What is Service Discovery (e.g., Netflix Eureka), and why is it necessary in a Spring Cloud environment?

Mid
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q62.
Explain the role of a Spring Cloud Gateway. How does it differ from a traditional Load Balancer?

Mid
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q63.
What is the difference between RestTemplate, WebClient, and Feign Client for inter-service communication, and which would you choose today?

Mid
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q64.
Explain the difference between Spring MVC and Spring WebFlux, and when should you choose a reactive stack over a servlet-based one?

Mid
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q65.
Explain the concepts of Mono and Flux. When would you return one over the other?

Mid
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q66.
Explain how Spring Boot's Auto-configuration works and what happens under the hood when @EnableAutoConfiguration is triggered.

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q67.
What is the role of the @Configuration annotation and how does it differ from using @Component on a class with @Bean methods?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q68.
How does Spring resolve cyclic dependencies, and when does it fail to resolve them such as with constructor injection?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q69.
What are conditional annotations like @ConditionalOnMissingBean and @ConditionalOnProperty, and how do they enable auto-configuration?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q70.
Explain how Spring AOP uses Proxies. What is the difference between JDK Dynamic Proxies and CGLIB?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q71.
Explain the Spring Bean Lifecycle, including phases like instantiation, property population, and the role of BeanPostProcessor.

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q72.
What is the difference between BeanPostProcessor and BeanFactoryPostProcessor?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q73.
Explain the 'N+1 Select Problem' in the context of Spring Data JPA and how you can resolve it using Entity Graphs or Join Fetches.

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q74.
How does the @Transactional annotation work under the hood, including the role of AOP proxies and the self-invocation pitfall?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q75.
Explain the difference between Transaction Propagation and Transaction Isolation levels.

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q76.
Explain the Spring Security Filter Chain. How does a request get authenticated before reaching your controller?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q77.
Explain how OAuth2 / OpenID Connect login works in Spring Security and the role of the resource server and authorization server.

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q78.
What is the purpose of Spring Cloud Config Server, and how does it handle configuration changes without restarting services?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q79.
Explain the 'Sidecar' pattern in Spring Cloud and when you would use it.

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q80.
With the introduction of Virtual Threads in Java 21, when would you still choose WebFlux over Spring MVC?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q81.
What does Non-blocking I/O mean in the context of Spring WebFlux, and how does it improve scalability?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q82.
What is backpressure in reactive streams, and how does Spring WebFlux handle it?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.