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: 2–5 Years

Revise the Fresher Tier

  • Revise: Core Java Fundamentals (Fresher Tier)
  • Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)
  • Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)
  • Revise: Hibernate, SQL, Microservices, Maven & Git (Fresher Tier)

Intermediate Core Java

  • Intermediate OOP & Language Features — Interview Questions
  • Enums, Generics, Pass-by-Value & Imports — Interview Questions
  • Collections Internals & Scenarios — Interview Questions
  • JVM, Memory & Class Loading — Interview Questions
  • Exception Design & Serialization Edge Cases — Interview Questions

Java 8 Deep Dive & Stream Coding

  • Lambdas, Functional Interfaces & Method References — Interview Questions
  • Default Methods, Backward Compatibility & Optional — Interview Questions
  • Stream API Internals (Part 1) — Interview Questions
  • Stream API Internals (Part 2) — Interview Questions
  • Stream Coding Problems (Level 2, Part 1) — Interview Questions
  • Stream Coding Problems (Level 2, Part 2) — Interview Questions

Concurrency & Multithreading

  • Synchronization, Locks & Deadlocks — Interview Questions
  • Executors, ThreadLocal & Concurrent Collections — Interview Questions

Spring Framework In Depth

  • Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions
  • Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Spring Boot In Depth & Scenarios

  • Spring Boot Internals & Auto-Configuration — Interview Questions
  • Spring Boot Configuration, Profiles & Secrets — Interview Questions
  • Spring Boot Data, Transactions & Caching — Interview Questions
  • Spring Boot Testing, Error Pages & Deployment — Interview Questions
  • Spring Boot Performance, Scaling & Resilience — Interview Questions
  • Spring Boot Async, Events & Messaging — Interview Questions
  • Spring Boot Security Scenarios — Interview Questions
  • Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions
  • External APIs, Files, GraphQL & WebFlux — Interview Questions

Spring Security

  • Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions
  • Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions

Apache Kafka

  • Kafka Architecture, Topics & ZooKeeper vs KRaft — Interview Questions
  • Kafka Producers, Consumers, Reliability & Streams — Interview Questions
  • Kafka Security, Connect & Core Scenarios — Interview Questions
  • Kafka Production Scenarios — Interview Questions

Git, Maven & Gradle (Level II)

  • Git Workflows, Rebase & Conflict Handling — Interview Questions
  • Git Recovery, Hooks, Tags & Collaboration — Interview Questions
  • Maven Builds, Multi-Module Projects & Dependency Resolution — Interview Questions
  • Maven Profiles, settings.xml, Plugins & Quality Gates — Interview Questions
  • Gradle Fundamentals, Migration & Dependencies — Interview Questions
  • Gradle Performance, Plugins, Testing & Publishing — Interview Questions

Deployment & CI/CD

  • Sessions, CI/CD Pipelines, Rollbacks & Secrets — Interview Questions
  • Migrations, Zero-Downtime Releases, Containers & Monitoring — Interview Questions

JUnit 5 & Mockito

  • JUnit 5 — Interview Questions
  • Mockito Basics — Interview Questions
  • Mockito Advanced & Tricky Questions — Interview Questions
Chaturmind
← Java Interview Prep: 2–5 Years

Revise the Fresher Tier

  • Revise: Core Java Fundamentals (Fresher Tier)
  • Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)
  • Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)
  • Revise: Hibernate, SQL, Microservices, Maven & Git (Fresher Tier)

Intermediate Core Java

  • Intermediate OOP & Language Features — Interview Questions
  • Enums, Generics, Pass-by-Value & Imports — Interview Questions
  • Collections Internals & Scenarios — Interview Questions
  • JVM, Memory & Class Loading — Interview Questions
  • Exception Design & Serialization Edge Cases — Interview Questions

Java 8 Deep Dive & Stream Coding

  • Lambdas, Functional Interfaces & Method References — Interview Questions
  • Default Methods, Backward Compatibility & Optional — Interview Questions
  • Stream API Internals (Part 1) — Interview Questions
  • Stream API Internals (Part 2) — Interview Questions
  • Stream Coding Problems (Level 2, Part 1) — Interview Questions
  • Stream Coding Problems (Level 2, Part 2) — Interview Questions

Concurrency & Multithreading

  • Synchronization, Locks & Deadlocks — Interview Questions
  • Executors, ThreadLocal & Concurrent Collections — Interview Questions

Spring Framework In Depth

  • Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions
  • Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Spring Boot In Depth & Scenarios

  • Spring Boot Internals & Auto-Configuration — Interview Questions
  • Spring Boot Configuration, Profiles & Secrets — Interview Questions
  • Spring Boot Data, Transactions & Caching — Interview Questions
  • Spring Boot Testing, Error Pages & Deployment — Interview Questions
  • Spring Boot Performance, Scaling & Resilience — Interview Questions
  • Spring Boot Async, Events & Messaging — Interview Questions
  • Spring Boot Security Scenarios — Interview Questions
  • Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions
  • External APIs, Files, GraphQL & WebFlux — Interview Questions

Spring Security

  • Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions
  • Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions

Apache Kafka

  • Kafka Architecture, Topics & ZooKeeper vs KRaft — Interview Questions
  • Kafka Producers, Consumers, Reliability & Streams — Interview Questions
  • Kafka Security, Connect & Core Scenarios — Interview Questions
  • Kafka Production Scenarios — Interview Questions

Git, Maven & Gradle (Level II)

  • Git Workflows, Rebase & Conflict Handling — Interview Questions
  • Git Recovery, Hooks, Tags & Collaboration — Interview Questions
  • Maven Builds, Multi-Module Projects & Dependency Resolution — Interview Questions
  • Maven Profiles, settings.xml, Plugins & Quality Gates — Interview Questions
  • Gradle Fundamentals, Migration & Dependencies — Interview Questions
  • Gradle Performance, Plugins, Testing & Publishing — Interview Questions

Deployment & CI/CD

  • Sessions, CI/CD Pipelines, Rollbacks & Secrets — Interview Questions
  • Migrations, Zero-Downtime Releases, Containers & Monitoring — Interview Questions

JUnit 5 & Mockito

  • JUnit 5 — Interview Questions
  • Mockito Basics — Interview Questions
  • Mockito Advanced & Tricky Questions — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: 2–5 YearsRevise the Fresher Tier
✓ FreeIntermediate· 49 min read

Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)

Every fresher-level Spring question — IoC and DI, Boot fundamentals, REST, MVC internals — 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 Fresher to 2 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 Core

Spring IoC, Dependency Injection & Beans — Interview Questions — open the lesson

  • What is Spring? — Spring is an open-source framework for building Java applications. At its core is an IoC container that creates your objects (beans) and wires their dependencies together.
  • What are the advantages of the Spring framework? — Loose coupling through DI, easy unit testing (inject mocks), declarative transactions and security, consistent data access (including exception translation), and a huge ecosystem: Spring Boot, Data, Security, Cloud and Batch.
  • What are the main modules of the Spring framework? — - Core container: Beans, Core, Context, SpEL. - AOP. - Data access: JDBC, ORM, transactions. - Web: Spring MVC and WebFlux. - Messaging. - Test.
  • What's the difference between Spring and Spring Boot? — Spring Framework provides the building blocks: DI, MVC, transactions. Spring Boot is an opinionated layer on top that makes those blocks quick to use.
  • What is a Spring bean? — A bean is an object whose lifecycle is created, configured and managed by the Spring container. Any class can become a bean, either through a stereotype annotation (@Component, @Service, @Repository, @Controller) found by component scanning, or through an @Bean…
  • What are IoC and DI? — Inversion of Control is the principle: your code doesn't create or control its collaborators; a framework does.
  • What is the role of the IoC container? — The container reads bean definitions (from component scanning, @Configuration classes or XML), instantiates beans, resolves and injects their dependencies, applies post-processors (which is how AOP proxies, @Autowired and @Value work), runs lifecycle callbacks, and…
  • What types of IoC container does Spring have? — BeanFactory, the basic container, which creates beans lazily on request, and ApplicationContext, which extends it and is what every real application uses.
  • What are @Configuration and @Bean used for? — @Configuration marks a class as a source of bean definitions. @Bean on one of its methods registers the method's return value as a bean.
  • What is the best way to inject beans, and why? — Constructor injection. - Dependencies are explicit and required. - Fields can be final, so the object is immutable and fully initialised from the start. - It's trivially testable with new Service(mockRepo), with no Spring context needed. - A large constructor makes it…

Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions — open the lesson

  • What's the difference between constructor injection and setter injection? — Constructor injection supplies dependencies when the object is created. They're mandatory, can be final, and the object is never half-built.
  • What bean scopes does Spring support? — - singleton (the default): one instance per container. - prototype: a new instance every time the bean is requested. - Web-aware scopes: - request: one per HTTP request. - session: one per HTTP session. - application: one per ServletContext. - websocket: one per WebSocket…
  • When would you use singleton scope, and when prototype? — Singleton for stateless services, repositories, clients and configuration, which is the vast majority of beans.
  • What is the default bean scope? — Singleton. Exactly one instance per Spring ApplicationContext, created eagerly at startup (unless marked @Lazy), and shared by everything that injects it.
  • Are singleton beans thread-safe? — Spring doesn't make them thread-safe. It creates one instance and shares it across all request threads. They're safe if they're stateless (only final references to other stateless beans), which is how Controller, Service and Repository beans should be written.
  • Can a project have multiple Spring configuration files? — Yes, and that's normal. Split configuration by concern (SecurityConfig, PersistenceConfig, KafkaConfig), and combine the pieces through component scanning or @Import(...).
  • Name some design patterns used in the Spring framework. — Compared side by side in the full answer (table) — know each row.
  • How does the prototype scope work? — Every time a prototype bean is requested from the container (by getBean, or by being injected into another bean), Spring creates a new instance and injects its dependencies.
  • What are Spring profiles, and how do you use them? — Profiles let you register beans or load configuration only in certain environments, such as dev, test or prod.
  • What is Spring WebFlux, and how is it different from Spring MVC? — WebFlux (Spring 5+) is Spring's reactive, non-blocking web stack, built on Project Reactor (Mono, Flux), and usually run on Netty.
  • Scenario: annotations or XML to configure beans on a new project? — Annotations and Java config for virtually all new projects. They're type-safe, refactor-friendly, sit next to the code, and are what Spring Boot is built around.
  • Scenario: a large project has many interdependent beans. How do you keep dependencies clean? — - Use constructor injection throughout, so dependencies are visible. - Depend on interfaces. - Organise code by feature, with a configuration class per module, and expose only the module's public services. - Use profiles for environment differences. - Watch for cycles and…
  • Scenario: a singleton bean must be thread-safe. What are your options? — 1. Make it stateless, keeping per-request data in local variables or method parameters. This is the best option. 2.

Spring Boot Essentials

Spring Boot Fundamentals — Interview Questions — open the lesson

  • What is Spring Boot? — Spring Boot is an opinionated extension of the Spring Framework for building production-ready, standalone applications with minimal setup.
  • What are the features of Spring Boot? — - Auto-configuration. - Starter dependencies. - Embedded servers: Tomcat (the default), Jetty or Undertow. - Externalised configuration: properties, YAML, environment variables, profiles. - Actuator: health, metrics, info, and other operational endpoints. - DevTools:…
  • What are the advantages of Spring Boot? — - Much less configuration. - Faster project setup. - Consistent dependency versions. - Simple deployment, as one runnable JAR. - Production monitoring out of the box. - Smooth integration with the rest of the Spring ecosystem (Data, Security, Cloud, Kafka).
  • What are the key components of Spring Boot? — 1. Starters: curated dependency bundles. 2. Auto-configuration: conditional @Configuration classes. 3. SpringApplication: the bootstrap class that creates the context and starts the server. 4.
  • Why is Spring Boot preferred over plain Spring? — With plain Spring, you choose and align library versions, configure the DispatcherServlet, data sources, transaction managers and JSON converters yourself, and deploy a WAR file to an external server.
  • How does Spring Boot work internally? — SpringApplication.run() does the following: 1. Creates the ApplicationContext. 2. Loads configuration from properties, environment variables and profiles. 3.
  • What are Spring Boot starter dependencies? — Starters are dependency descriptors that pull in a tested, compatible set of libraries for a feature, and trigger the matching auto-configuration.
  • How does a Spring Boot application start? — The main method calls SpringApplication.run(App.class, args). That: 1. Prepares the environment (properties, profiles). 2.
  • What does @SpringBootApplication do internally? — It's a shortcut for three annotations: - @SpringBootConfiguration: a specialised @Configuration. - @EnableAutoConfiguration: imports the conditional auto-configuration classes. - @ComponentScan: scans the annotated class's package and its sub-packages.
  • What is Spring Initializr? — A project generator, at start.spring.io, which is also built into IntelliJ, VS Code and the Spring CLI. You pick the build tool, language, Boot version, Java version and dependencies, and it generates a ready-to-run project skeleton with the correct parent POM or plugins, the…
  • What is a Spring bean (in a Boot application)? — An object created and managed by the Spring container, with its dependencies injected and its lifecycle handled by Spring.
  • What is autowiring? — Autowiring is Spring automatically resolving and injecting a bean's dependencies, by type first, and then by name or qualifier to resolve ambiguity.

Spring Boot Runners, Servers & Configuration — Interview Questions — open the lesson

  • What is ApplicationRunner? — A callback interface. Any ApplicationRunner bean's run(ApplicationArguments args) method executes once, after the application context has started, and just before the app is reported as ready.
  • What is CommandLineRunner, and how does it differ from ApplicationRunner? — It serves the same purpose. The difference is the arguments: CommandLineRunner.run(String... args) receives the raw argument strings, while ApplicationRunner receives parsed ApplicationArguments, where you can query options (--name=value) separately from non-option…
  • What is the Spring Boot CLI, and what commands are commonly used? — A command-line tool for bootstrapping Spring Boot projects: - spring init: generate a project from Spring Initializr, for example spring init --dependencies=web,data-jpa demo. - spring help. - spring encodepassword: create a hashed password for Spring Security.
  • What is Spring Boot dependency management? — Spring Boot publishes a bill of materials (spring-boot-dependencies) that pins compatible versions of hundreds of libraries: Hibernate, Jackson, Tomcat, Kafka clients and more.
  • What happens when a starter brings in a library version that conflicts with another dependency? — Maven and Gradle each put only one version of an artifact on the classpath: - Maven picks the nearest declaration in the dependency tree ("nearest wins").
  • How do you change the embedded Tomcat port? — Set server.port — server: port: 9090 # application.yml
  • What is the default embedded server port? — 8080, for Tomcat, and also for Jetty, Undertow, and Netty in WebFlux. The management (Actuator) endpoints use the same port unless you set management.server.port.
  • Can you disable the embedded web server? — Yes. Set spring.main.web-application-type=none, and Spring Boot starts a plain application context with no web server.
  • How do you disable a specific auto-configuration class? — Use the exclude attribute, or a property — @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) public class App { }
  • Can you build a non-web application with Spring Boot? — Absolutely. Batch jobs, schedulers, message consumers and command-line tools all benefit from Boot's DI, configuration and auto-configuration without needing a web server.
  • Describe the flow of an HTTPS request through a Spring Boot application. — 1. TLS handshake and decryption: at the embedded server's HTTPS connector, or, often in production, at a load balancer or ingress in front of the app. 2.

Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions — open the lesson

  • What does @RestController do? — It marks a class as a web controller whose methods' return values are written directly to the HTTP response body, serialised to JSON by Jackson, instead of being resolved as view names.
  • What's the difference between @Controller and @RestController? — A @Controller method's return value is treated as a view name (Thymeleaf, JSP), unless the method is also annotated with @ResponseBody.
  • What's the difference between @RequestMapping and @GetMapping? — @RequestMapping is the general mapping annotation. It can match any HTTP method (set it with method = RequestMethod.GET), and it's commonly used at class level for a base path.
  • What's the difference between @SpringBootApplication and @EnableAutoConfiguration? — @EnableAutoConfiguration does one thing: it turns on Boot's conditional auto-configuration. @SpringBootApplication includes it, together with @SpringBootConfiguration (a @Configuration) and @ComponentScan.
  • How do you find the active profiles programmatically? — Inject the Environment, and call getActiveProfiles(). Use acceptsProfiles(Profiles.of("prod")) to check a condition.
  • What's the difference between WAR deployment and embedded containers? — A WAR is deployed into an externally installed servlet container (Tomcat, JBoss/WildFly), which hosts one or more applications.
  • What is Spring Boot Actuator? — Actuator adds production-ready operational endpoints under /actuator: - health, with liveness and readiness groups for Kubernetes. - info. - metrics, through Micrometer, exportable to Prometheus and others. - env, configprops, beans, mappings, loggers…
  • How do you enable Actuator? — Add spring-boot-starter-actuator, then configure which endpoints are exposed, and how they're secured — management: endpoints:
  • How do you list all the beans in the application? — Inject the ApplicationContext, and call getBeanDefinitionNames(). Or expose the /actuator/beans endpoint, which also shows each bean's type, scope and dependencies.
  • Can you check environment properties in a Spring Boot application? How? — Yes: - Inject the Environment, and call getProperty("key"), with an optional default and target type. - Inject single values with @Value("${key}"). - Bind groups of settings to a @ConfigurationProperties class, which is the preferred, type-safe option. - At runtime,…
  • How do you enable debug logging? — Set the log level of the loggers you care about — logging: level:
  • Why use the spring-boot-devtools dependency? — To speed up the development loop: - Automatic restart when classes change. It's fast because only your code's class loader is reloaded. - LiveReload for browser refresh. - Development-friendly defaults, such as template caching turned off. - Global settings through…

Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions — open the lesson

  • How do you test a Spring Boot application? — In layers: - Unit tests: plain JUnit 5 plus Mockito, with no Spring context. They're fast, and test business logic. - Slice tests: load only one layer. - @WebMvcTest for controllers, with MockMvc. - @DataJpaTest for repositories, against an embedded database or…
  • What is the purpose of unit testing? — To verify that small units of code (a method or a class) behave correctly in isolation. It catches bugs early, documents the intended behaviour, and gives you the confidence to refactor.
  • How do JUnit and Mockito help with unit testing? — JUnit 5 is the test framework. It provides @Test, assertions, the lifecycle (@BeforeEach), parameterised tests, and the runner.
  • What's the difference between @Mock and @InjectMocks? — @Mock creates a fake dependency. @InjectMocks creates the real object under test, and injects the @Mock fields into it, through the constructor, setters or fields.
  • What is the role of @SpringBootTest? — It starts the full application context: all beans, auto-configuration and properties. That lets you test how components work together.
  • How do you handle exceptions in a Spring Boot application? — Centralise error handling in a @RestControllerAdvice class, with @ExceptionHandler methods that map exceptions to HTTP responses.
  • What is the purpose of pom.xml in a Maven project? — It's the Project Object Model. It declares the project's coordinates (groupId, artifactId, version), packaging, dependencies, plugins, build settings, properties and profiles.
  • What role does auto-configuration play in a Spring Boot application? — It creates the infrastructure beans your app needs, based on what's on the classpath and in your properties. - spring-boot-starter-data-jpa plus a JDBC URL gives you a DataSource, an EntityManagerFactory and a transaction manager. - spring-boot-starter-web gives you…
  • Can you customise a specific auto-configuration? — Yes, in increasing order of control: 1. Properties (spring.datasource.hikari.maximum-pool-size, spring.jackson.default-property-inclusion). 2.
  • How do you disable specific auto-configuration classes? — Use @SpringBootApplication(exclude = DataSourceAutoConfiguration.class), or excludeName with a fully qualified class name, or the spring.autoconfigure.exclude property (which can differ per profile).
  • What is the purpose of spring-boot-starter-parent? — It's a Maven parent POM that provides: - dependency management, through the Boot BOM; - a sensible Java version and UTF-8 encoding; - plugin configuration (compiler with -parameters, surefire, the Spring Boot plugin's repackage goal); - resource filtering for…
  • How do starters simplify Maven or Gradle configuration? — One starter replaces a list of individually chosen, individually versioned dependencies. For example, spring-boot-starter-web brings Spring MVC, Jackson, validation support and embedded Tomcat.

REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions — open the lesson

  • How do you create a REST API in Spring Boot? — 1. Add spring-boot-starter-web. 2. Create a @RestController, and map methods with @GetMapping, @PostMapping, @PutMapping, @PatchMapping and @DeleteMapping. 3.
  • What is API versioning, and how can you implement it? — Versioning lets you make breaking changes without breaking existing clients. Several versions run side by side while clients migrate.
  • What are the REST API best practices? — - Resource-oriented plural nouns (/orders/{id}/items), not verbs. - Correct HTTP methods, with their semantics: GET is safe; PUT and DELETE are idempotent. - Correct status codes. - Stateless requests. - Consistent error format (Problem Details). - Pagination, filtering and…
  • What is ResponseEntity used for? — It represents the whole HTTP response, so you control the status code, headers and body in one return value. For example: 201 with a Location header, 204 with no body, or conditional 304 responses with an ETag.
  • What status code should a DELETE endpoint return? — - 204 No Content when the deletion succeeded and there's nothing to return. This is the most common case. - 200 OK if you return a body, such as the deleted resource or a status message. - 202 Accepted if the deletion is queued asynchronously. - For a resource that doesn't…
  • What is Swagger? — Swagger is the tooling ecosystem around the OpenAPI Specification, the standard, machine-readable description of REST APIs (endpoints, parameters, schemas, authentication).
  • How does Swagger help document APIs? — springdoc builds the OpenAPI document from your code: mappings, DTOs, validation annotations. That keeps the documentation in sync with the implementation.
  • Which embedded servers does Spring Boot support, and which is the default? — Tomcat (the default, with spring-boot-starter-web), Jetty and Undertow for servlet applications, and Reactor Netty as the default for WebFlux.
  • How does Spring Boot decide which embedded server to use if several are on the classpath? — It doesn't depend on classpath order. The servlet web-server auto-configuration imports the Tomcat, Jetty and Undertow configurations in that fixed order.
  • How do you replace the default server with a different one? — Exclude Tomcat from the web starter, and add the other server's starter — <dependency> <groupId>org.springframework.boot</groupId>
  • What are the most important Spring Boot annotations? — Grouped by purpose.
  • Can you use @Component instead of @Service and @Repository? Then why use them? — Yes. Technically, all three register a bean through component scanning. The specialised stereotypes still matter: - @Repository activates persistence exception translation, which turns vendor-specific exceptions (SQLException, Hibernate exceptions) into Spring's…

Spring MVC

Spring MVC Architecture & DispatcherServlet — Interview Questions — open the lesson

  • What is Spring MVC? — Spring MVC is Spring's servlet-based web framework, built around the Model–View–Controller pattern and a central front controller, the DispatcherServlet.
  • What are the core components of Spring MVC? — - DispatcherServlet: the front controller. - HandlerMapping: finds which handler matches the request. - HandlerAdapter: invokes the handler. - Controller: your @Controller or @RestController. - Model: the data for the view. - ViewResolver: turns a view name into…
  • Describe the lifecycle of a Spring MVC request. — 1. The servlet container passes the request through its filters (security, CORS, encoding) to the DispatcherServlet. 2.
  • What role does the DispatcherServlet play? How are controllers and view resolvers wired together during a request? — The DispatcherServlet is the front controller. Every request goes through it, and it orchestrates the whole flow: it delegates handler lookup to HandlerMappings, invocation to HandlerAdapters, view resolution to ViewResolvers, and errors to HandlerExceptionResolvers.
  • What is the role of the WebApplicationContext? — It's an ApplicationContext that is aware of the web environment. It knows its ServletContext, and it supports the request, session and application scopes.
  • How do you configure Spring MVC in a web application? — In Spring Boot: add spring-boot-starter-web, and you're done. The DispatcherServlet, Jackson converters, static-resource handling and error pages are all auto-configured.
  • What role does web.xml or Java config play in setting up Spring MVC? — It's where the servlet container is told about Spring. It declares the DispatcherServlet and its URL mapping (usually /), points it at its configuration, and optionally registers ContextLoaderListener and filters.
  • How do you set up Spring MVC without web.xml? — Servlet 3.0+ containers discover a WebApplicationInitializer automatically. The easiest route is to extend AbstractAnnotationConfigDispatcherServletInitializer — public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override…
  • How do servlets and listeners contribute to the configuration? — - Servlets handle requests. The DispatcherServlet is the servlet in a Spring MVC app. - Listeners react to lifecycle events.

Spring MVC Request Mapping & Controllers — Interview Questions — open the lesson

  • What is the purpose of @RequestMapping? — It maps web requests to controller classes and methods. It matches on the path, and optionally on the HTTP method, parameters, headers, and content types (consumes/produces).
  • How do you define method-level mappings in a controller? — Annotate each handler method with @GetMapping, @PostMapping, @PutMapping, @PatchMapping or @DeleteMapping (or @RequestMapping with method).
  • What attributes does @RequestMapping have? — Compared side by side in the full answer (table) — know each row.
  • How does @RequestMapping handle different HTTP methods? — Through the method attribute, or the composed shortcuts. The same path can map to different methods for different verbs.
  • What's the difference between @Controller and @RestController? — @Controller is for MVC controllers, whose methods usually return a view name plus model data, rendered as HTML by a template engine.
  • When would you use @RestController instead of @Controller? — For APIs consumed by programs: SPAs (React, Angular), mobile apps, and other services. Use @Controller when the server renders HTML pages (Thymeleaf, JSP), or when one controller mixes pages with a few JSON endpoints (annotated with @ResponseBody).
  • How does response handling differ between the two? — With @Controller, a returned String is a view name: ViewResolver → View → HTML, with the Model supplying the data.
  • What does using @RestController mean for data serialisation? — Every return value is serialised by Jackson (by default), so the shape of your Java types becomes your API contract.

Spring MVC Forms, Views & Interceptors — Interview Questions — open the lesson

  • How do you manage form data in Spring MVC? — Bind the form fields to a form-backing object with @ModelAttribute. Spring's data binder matches request parameters to properties by name, and converts their types.
  • How do you handle form submission? — Use a @PostMapping method that takes the @Valid @ModelAttribute object and a BindingResult. If there are errors, redisplay the form.
  • What is @ModelAttribute for? — It has two roles: 1. On a parameter, it binds request data to an object, creating or retrieving it, and adds that object to the model. 2.
  • How does form validation work in Spring MVC? — Annotate the form class with Bean Validation constraints (@NotBlank, @Email, @Size, @Pattern, and custom ones), and trigger validation with @Valid (or @Validated for validation groups).
  • What is a ViewResolver, and how does it work? — A ViewResolver turns the logical view name a controller returns ("order-details") into an actual View object that renders the output.
  • What types of ViewResolver exist? — - InternalResourceViewResolver: JSPs. - ThymeleafViewResolver: Thymeleaf. This is Spring Boot's usual choice. - FreeMarkerViewResolver: FreeMarker. - BeanNameViewResolver: a view defined as a bean whose name matches the view name. - ContentNegotiatingViewResolver:…
  • How does InternalResourceViewResolver work? — It builds a path from prefix + view name + suffix, and forwards the request to that JSP inside the web application.
  • What are the advantages of ContentNegotiatingViewResolver? — One controller method can serve several formats: HTML for browsers, JSON or XML for API clients. The resolver chooses the view from the requested media type (the Accept header, or a path extension or parameter if configured), and delegates to the matching view resolvers and…
  • How are interceptors used in Spring MVC? — A HandlerInterceptor runs code before and after the handler executes. It's used for cross-cutting web concerns that need to know which handler runs: request timing, audit logging, tenant resolution, locale or theme changes, simple API-key checks, and adding common model…
  • What methods does the HandlerInterceptor interface have? — 1. preHandle: runs before the handler. Returning false stops processing. 2. postHandle: runs after the handler, before the view renders.
  • How do you apply an interceptor globally? — Register it in a WebMvcConfigurer. Without path patterns, it applies to every handler. Narrow it with addPathPatterns and excludePathPatterns.
  • What's the difference between a Spring MVC interceptor and a servlet filter? — Compared side by side in the full answer (table) — know each row.

Spring MVC Exceptions, Security & Dependency Injection — Interview Questions — open the lesson

  • How is exception handling done in Spring MVC? — There are four levels: 1. @ExceptionHandler methods inside a controller, which handle that controller's exceptions only. 2.
  • How do you configure a global exception handler with @ControllerAdvice? — Create a class annotated with @RestControllerAdvice (or @ControllerAdvice for view-based apps), and add @ExceptionHandler methods.
  • What is @ExceptionHandler used for? — It marks a method that handles specific exception types thrown from handler methods, and builds the error response: status, body and headers.
  • How does Spring MVC tell different exception types apart? — It matches the thrown exception against the types declared in the @ExceptionHandler annotations, choosing the closest match in the class hierarchy.
  • What are the options for securing a Spring MVC application? — Spring Security is the standard choice. It gives you: - Authentication: form login, HTTP Basic, OAuth2/OIDC login, JWT resource servers, LDAP, SAML. - Authorisation, at URL level (authorizeHttpRequests) and at method level (@PreAuthorize). - Protection against attacks:…
  • How does Spring Security integrate with Spring MVC? — Through a servlet filter chain. DelegatingFilterProxy passes each request to Spring Security's FilterChainProxy, which runs the ordered security filters (authentication, exception translation, authorisation) before the request reaches the DispatcherServlet.
  • What are the common challenges in securing a Spring MVC application? — - Getting authentication and authorisation right, especially authorisation on every endpoint (broken access control is the top OWASP risk). - Session management: fixation, timeouts, concurrent sessions. - CSRF for cookie-based sessions, and XSS in views. - Injection attacks.…
  • How do you configure method-level security? — Enable it with @EnableMethodSecurity (Spring Security 6), then annotate service or controller methods: - @PreAuthorize and @PostAuthorize take SpEL expressions. - @Secured and @RolesAllowed are available when enabled.
  • What does dependency injection mean in the context of Spring MVC? — Controllers, services, repositories, interceptors and advice classes are all Spring beans. The container supplies each one's collaborators, instead of the classes creating them.
  • How does Spring MVC use dependency injection with controllers? — Controllers are discovered by component scanning (@Controller/@RestController), and created as singletons.
  • What types of dependency injection does Spring support? — Constructor, setter and field injection. Use constructor injection for required dependencies, and setter injection for optional ones.
  • What are the benefits of dependency injection in web applications? — - Testability: controllers tested with mocked services in @WebMvcTest. - Loose coupling: swap implementations per environment. - Centralised configuration. - Consistent lifecycles: pooled clients and data sources, managed once. - Cross-cutting features through proxies:…

Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions — open the lesson

  • How does Spring MVC support data binding? — Spring's WebDataBinder copies request data (query parameters, form fields, path variables) into handler arguments and objects, converting types along the way through its ConversionService (String → int, LocalDate, enums, …).
  • What does @RequestParam do? — It binds a query-string or form parameter to a method argument, with optional required, defaultValue and type conversion.
  • How do you customise data binding for complex objects? — In increasing scope: - @InitBinder methods in a controller or @ControllerAdvice: register custom editors, set allowed or disallowed fields, trim strings. - Global Converter/Formatter beans, registered through WebMvcConfigurer.addFormatters, or simply as beans in…
  • What are the challenges with data binding, and how do you address them? — - Type-conversion errors: handle them through BindingResult, or a global handler that returns clear 400 messages. - Complex and nested types: use converters and formatters. - Validation: Bean Validation, plus custom validators. - Security, meaning mass assignment: an…
  • How do you handle static resources in Spring MVC? — - In Spring Boot, files in classpath:/static/, /public/, /resources/ or /META-INF/resources/ are served automatically from the root path.
  • How do you configure Spring MVC to serve CSS, JavaScript or images? — Put them in a static location (Boot), or map a URL pattern to a location with addResourceHandlers. Reference them from templates with context-aware URLs (for example, Thymeleaf's @{/css/app.css}), so they keep working behind a context path.
  • How does resource handling affect application performance? — Static files are a large share of page weight, so how they're served matters: - HTTP caching: long Cache-Control max-age for immutable files, plus ETag or Last-Modified for validation. - Cache-busting versioned URLs: Spring's VersionResourceResolver produces…
  • How does Spring manage resources differently in a web application context? — Spring's Resource abstraction loads files uniformly from different places: - classpath: → ClassPathResource; - file: → FileSystemResource; - http: → UrlResource; - and, in a web application context, paths relative to the web app root, resolved as…
  • What is the role of @PathVariable? — It binds a segment of the URL path (a URI template variable) to a method parameter. It identifies which resource the request is about, as in /orders/{orderId}.
  • How do you extract values from a URL with @PathVariable? — Declare placeholders in the mapping, and matching parameters (by name, or @PathVariable("id")). Spring converts the text to the parameter type.
  • What should you consider when designing URLs with @PathVariable? — - Use path variables for identity (/orders/42), and query parameters for filters and options (/orders?status=PAID). - Use clear, stable names and plural nouns, and keep nesting shallow (/customers/7/orders, not five levels deep). - Avoid ambiguity between literal and…
  • How does @PathVariable interact with other request mappings? — Class-level and method-level patterns are combined, so variables can appear at either level. @PathVariable works alongside @RequestParam, @RequestBody and headers in the same method.

Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions — open the lesson

  • How does Spring MVC use a LocaleResolver? — A LocaleResolver determines the locale of each request. MessageSource then uses it to pick translated messages (messages_hi.properties, messages_fr.properties), and formatters use it for dates and numbers.
  • How do you let users change the language dynamically? — Use a LocaleChangeInterceptor, which reads a request parameter such as ?lang=hi, together with a resolver that can store the choice (session or cookie).
  • What are @SessionAttributes and @CookieValue for? — - @SessionAttributes("wizardForm"), on a controller class, stores the named model attributes in the HTTP session across requests.
  • What are the security considerations for @SessionAttributes and @CookieValue? — - Sessions: don't store secrets or large objects. Always clear wizard state when it's done. Protect against session fixation (Spring Security changes the session ID on login).
  • How do you test Spring MVC applications? — - Unit-test controllers with mocked services. - Slice-test the web layer with @WebMvcTest and MockMvc, which performs requests without a real server and checks the status, headers, JSON and views. - Integration-test the whole stack with @SpringBootTest, using MockMvc,…
  • Which frameworks are used to test Spring MVC components? — - JUnit 5 (the test engine). - Mockito (mocks). - Spring Test / Spring Boot Test: MockMvc, @WebMvcTest, @SpringBootTest, test slices. - AssertJ and Hamcrest (assertions), plus JsonPath for JSON. - Testcontainers (real databases and brokers). - WireMock (stubbed external…
  • How do you mock Spring MVC dependencies for unit tests? — In a pure unit test, create the controller with new, passing Mockito mocks. In a web-slice test, @WebMvcTest loads only the MVC components, and @MockitoBean (Boot 3.4+, formerly @MockBean) replaces each service bean in the context with a mock that you stub.
  • What are the best practices for integration testing Spring MVC? — - Use @SpringBootTest sparingly, for real end-to-end flows. - Use real infrastructure through Testcontainers (@ServiceConnection) instead of in-memory substitutes. - Stub third-party HTTP services with WireMock. - Isolate test data: transactional rollback, or cleaning up…
  • How does Spring MVC support file uploads? — Multipart requests (enctype="multipart/form-data") are parsed by a MultipartResolver. Spring Boot auto-configures StandardServletMultipartResolver, which uses the Servlet API's built-in multipart support.
  • What configuration is needed to enable file uploads? — In Spring Boot, multipart support is on by default. Set the limits — spring: servlet:
  • How do you handle a file upload in a controller? — Take a MultipartFile parameter with @RequestParam (or @RequestPart for mixed JSON-plus-file requests). Validate it, then stream it to storage.
  • What are the common file-upload problems, and their solutions? — Compared side by side in the full answer (table) — know each row.
  • How can Spring MVC be integrated with technologies such as JPA or WebSocket? — - JPA: controllers call services that use Spring Data JPA repositories, with @Transactional in the service layer.
  • What Spring MVC features help high-traffic applications? — - Asynchronous request processing frees container threads during slow I/O. - Caching with @Cacheable and HTTP caching (ETags). - Connection pooling (HikariCP) and HTTP client pooling. - Pagination and lean DTOs. - Compression. - Virtual threads…
  • How do you implement caching in Spring MVC? — Enable Spring's cache abstraction with @EnableCaching, annotate service methods with @Cacheable, and evict with @CacheEvict (or update with @CachePut) when the data changes.
  • What strategies exist for asynchronous processing in Spring MVC? — A handler can return a type that lets the container thread go back to the pool while the work finishes elsewhere: - Callable<T>: Spring runs it on a task executor. - DeferredResult<T>: completed later by another thread, for example when a message arrives. -…
  • How do you scale a Spring MVC application horizontally? — - Run multiple identical instances behind a load balancer. - Keep the application stateless: token-based authentication, or sessions externalised to Spring Session with Redis, so any instance can serve any request. - Share caches (Redis), and make scheduled jobs cluster-safe…

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: Collections, Threads, Java 8 & Coding (Fresher Tier)

Next

Revise: Hibernate, SQL, Microservices, Maven & Git (Fresher Tier)

AI Tutor

Lesson: Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)

Quick actions

AI responses can be inaccurate. Verify critical information.