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
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 IoC, Dependency Injection & Beans — Interview Questions — open the lesson
@Component, @Service, @Repository, @Controller) found by component scanning, or through an @Bean…@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…BeanFactory, the basic container, which creates beans lazily on request, and ApplicationContext, which extends it and is what every real application uses.@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.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
final, and the object is never half-built.ServletContext. - websocket: one per WebSocket…ApplicationContext, created eagerly at startup (unless marked @Lazy), and shared by everything that injects it.SecurityConfig, PersistenceConfig, KafkaConfig), and combine the pieces through component scanning or @Import(...).getBean, or by being injected into another bean), Spring creates a new instance and injects its dependencies.dev, test or prod.Mono, Flux), and usually run on Netty.Spring Boot Fundamentals — Interview Questions — open the lesson
@Configuration classes. 3. SpringApplication: the bootstrap class that creates the context and starts the server. 4.DispatcherServlet, data sources, transaction managers and JSON converters yourself, and deploy a WAR file to an external server.SpringApplication.run() does the following: 1. Creates the ApplicationContext. 2. Loads configuration from properties, environment variables and profiles. 3.main method calls SpringApplication.run(App.class, args). That: 1. Prepares the environment (properties, profiles). 2.@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.Spring Boot Runners, Servers & Configuration — Interview Questions — open the lesson
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.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…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.spring-boot-dependencies) that pins compatible versions of hundreds of libraries: Hibernate, Jackson, Tomcat, Kafka clients and more.server.port — server: port: 9090 # application.ymlmanagement.server.port.spring.main.web-application-type=none, and Spring Boot starts a plain application context with no web server.exclude attribute, or a property — @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) public class App { }Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions — open the lesson
@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.@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.@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.@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.Environment, and call getActiveProfiles(). Use acceptsProfiles(Profiles.of("prod")) to check a condition./actuator: - health, with liveness and readiness groups for Kubernetes. - info. - metrics, through Micrometer, exportable to Prometheus and others. - env, configprops, beans, mappings, loggers…spring-boot-starter-actuator, then configure which endpoints are exposed, and how they're secured — management: endpoints:ApplicationContext, and call getBeanDefinitionNames(). Or expose the /actuator/beans endpoint, which also shows each bean's type, scope and dependencies.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,…logging: level: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
@WebMvcTest for controllers, with MockMvc. - @DataJpaTest for repositories, against an embedded database or…@Test, assertions, the lifecycle (@BeforeEach), parameterised tests, and the runner.@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.@SpringBootTest? — It starts the full application context: all beans, auto-configuration and properties. That lets you test how components work together.@RestControllerAdvice class, with @ExceptionHandler methods that map exceptions to HTTP responses.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.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…spring.datasource.hikari.maximum-pool-size, spring.jackson.default-property-inclusion). 2.@SpringBootApplication(exclude = DataSourceAutoConfiguration.class), or excludeName with a fully qualified class name, or the spring.autoconfigure.exclude property (which can differ per profile).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…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
spring-boot-starter-web. 2. Create a @RestController, and map methods with @GetMapping, @PostMapping, @PutMapping, @PatchMapping and @DeleteMapping. 3./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…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.spring-boot-starter-web), Jetty and Undertow for servlet applications, and Reactor Netty as the default for WebFlux.<dependency> <groupId>org.springframework.boot</groupId>@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 Architecture & DispatcherServlet — Interview Questions — open the lesson
DispatcherServlet.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…DispatcherServlet. 2.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.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.spring-boot-starter-web, and you're done. The DispatcherServlet, Jackson converters, static-resource handling and error pages are all auto-configured.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.web.xml? — Servlet 3.0+ containers discover a WebApplicationInitializer automatically. The easiest route is to extend AbstractAnnotationConfigDispatcherServletInitializer — public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override…DispatcherServlet is the servlet in a Spring MVC app. - Listeners react to lifecycle events.Spring MVC Request Mapping & Controllers — Interview Questions — open the lesson
@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).@GetMapping, @PostMapping, @PutMapping, @PatchMapping or @DeleteMapping (or @RequestMapping with method).@RequestMapping have? — Compared side by side in the full answer (table) — know each row.@RequestMapping handle different HTTP methods? — Through the method attribute, or the composed shortcuts. The same path can map to different methods for different verbs.@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.@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).@Controller, a returned String is a view name: ViewResolver → View → HTML, with the Model supplying the data.@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
@ModelAttribute. Spring's data binder matches request parameters to properties by name, and converts their types.@PostMapping method that takes the @Valid @ModelAttribute object and a BindingResult. If there are errors, redisplay the form.@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.@NotBlank, @Email, @Size, @Pattern, and custom ones), and trigger validation with @Valid (or @Validated for validation groups).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.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:…InternalResourceViewResolver work? — It builds a path from prefix + view name + suffix, and forwards the request to that JSP inside the web application.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…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…HandlerInterceptor interface have? — 1. preHandle: runs before the handler. Returning false stops processing. 2. postHandle: runs after the handler, before the view renders.WebMvcConfigurer. Without path patterns, it applies to every handler. Narrow it with addPathPatterns and excludePathPatterns.Spring MVC Exceptions, Security & Dependency Injection — Interview Questions — open the lesson
@ExceptionHandler methods inside a controller, which handle that controller's exceptions only. 2.@ControllerAdvice? — Create a class annotated with @RestControllerAdvice (or @ControllerAdvice for view-based apps), and add @ExceptionHandler methods.@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.@ExceptionHandler annotations, choosing the closest match in the class hierarchy.authorizeHttpRequests) and at method level (@PreAuthorize). - Protection against attacks:…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.@EnableMethodSecurity (Spring Security 6), then annotate service or controller methods: - @PreAuthorize and @PostAuthorize take SpEL expressions. - @Secured and @RolesAllowed are available when enabled.@Controller/@RestController), and created as singletons.@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
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, …).@RequestParam do? — It binds a query-string or form parameter to a method argument, with optional required, defaultValue and type conversion.@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…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…classpath:/static/, /public/, /resources/ or /META-INF/resources/ are served automatically from the root path.addResourceHandlers. Reference them from templates with context-aware URLs (for example, Thymeleaf's @{/css/app.css}), so they keep working behind a context path.Cache-Control max-age for immutable files, plus ETag or Last-Modified for validation. - Cache-busting versioned URLs: Spring's VersionResourceResolver produces…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…@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}.@PathVariable? — Declare placeholders in the mapping, and matching parameters (by name, or @PathVariable("id")). Spring converts the text to the parameter type.@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…@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
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.LocaleChangeInterceptor, which reads a request parameter such as ?lang=hi, together with a resolver that can store the choice (session or cookie).@SessionAttributes and @CookieValue for? — - @SessionAttributes("wizardForm"), on a controller class, stores the named model attributes in the HTTP session across requests.@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).@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,…MockMvc, @WebMvcTest, @SpringBootTest, test slices. - AssertJ and Hamcrest (assertions), plus JsonPath for JSON. - Testcontainers (real databases and brokers). - WireMock (stubbed external…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.@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…enctype="multipart/form-data") are parsed by a MultipartResolver. Spring Boot auto-configures StandardServletMultipartResolver, which uses the Servlet API's built-in multipart support.spring: servlet:MultipartFile parameter with @RequestParam (or @RequestPart for mixed JSON-plus-file requests). Validate it, then stream it to storage.@Transactional in the service layer.@Cacheable and HTTP caching (ETags). - Connection pooling (HikariCP) and HTTP client pooling. - Pagination and lean DTOs. - Compression. - Virtual threads…@EnableCaching, annotate service methods with @Cacheable, and evict with @CacheEvict (or update with @CachePut) when the data changes.Callable<T>: Spring runs it on a task executor. - DeferredResult<T>: completed later by another thread, for example when a message arrives. -…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.