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: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
Chaturmind
← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: Fresher to 2 YearsSpring MVC
✓ FreeBeginner· 7 min read

Spring MVC Exceptions, Security & Dependency Injection — Interview Questions

Exception handling options, @ControllerAdvice and @ExceptionHandler, how exceptions are matched, securing MVC apps with Spring Security 6, method-level security, and dependency injection in controllers.

Published September 25, 2026


How to use this lesson

Two themes run through this lesson. The first is centralised error handling, which interviewers expect you to have implemented. The second is Spring Security 6. Many prepared answers still describe WebSecurityConfigurerAdapter, which no longer exists. Give the current API.

Q1. How is exception handling done in Spring MVC?

Short answer: There are four levels:

  1. @ExceptionHandler methods inside a controller, which handle that controller's exceptions only.
  2. @ControllerAdvice / @RestControllerAdvice: global handlers shared by all controllers.
  3. @ResponseStatus on custom exception classes, to map an exception to a status code.
  4. HandlerExceptionResolver implementations, for full low-level control.

Spring Boot adds a fallback /error endpoint, BasicErrorController, for anything that isn't handled.

Key points to cover:

  • ResponseStatusException lets you throw a status code directly: throw new ResponseStatusException(HttpStatus.NOT_FOUND, "order 42 not found").

Learn it in depth → Spring Exception Handling

Q2. How do you configure a global exception handler with @ControllerAdvice?

Short answer: Create a class annotated with @RestControllerAdvice (or @ControllerAdvice for view-based apps), and add @ExceptionHandler methods. It applies to all controllers, unless you narrow it (basePackages, annotations, assignableTypes).

@RestControllerAdvice
class GlobalExceptionHandler extends ResponseEntityExceptionHandler {   // also handles Spring's built-in MVC exceptions

    @ExceptionHandler(ResourceNotFoundException.class)
    ProblemDetail handleNotFound(ResourceNotFoundException ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    ProblemDetail handleUnexpected(Exception ex) {
        log.error("Unhandled error", ex);                                   // full details in the logs only
        return ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, "Something went wrong");
    }
}

Key points to cover:

  • Turn on spring.mvc.problemdetails.enabled=true, so that Spring's own exceptions also use the RFC 9457 format.

Q3. What is @ExceptionHandler used for?

Short answer: It marks a method that handles specific exception types thrown from handler methods, and builds the error response: status, body and headers. Its parameters can include the exception, the request and the Locale. It can return a ProblemDetail, a ResponseEntity, a DTO, or a view (in MVC apps).

Q4. How does Spring MVC tell different exception types apart?

Short answer: It matches the thrown exception against the types declared in the @ExceptionHandler annotations, choosing the closest match in the class hierarchy. A handler for ResourceNotFoundException beats a handler for RuntimeException, which beats one for Exception.

  • Local handlers in the controller take priority over @ControllerAdvice ones.
  • Among several advice classes, @Order decides.
  • Nested causes are also matched.

Q5. What are the options for securing a Spring MVC application?

Short answer: 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: CSRF, session fixation, clickjacking headers, CORS configuration.

Also secure the rest of the stack:

  • HTTPS everywhere.
  • Validated input.
  • Parameterised queries.
  • Output encoding, which Thymeleaf does automatically.
  • Up-to-date dependencies.

Learn it in depth → Spring Security Overview

Q6. How does Spring Security integrate with Spring MVC?

Short answer: 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. In Spring Security 6, you configure it by declaring a SecurityFilterChain bean:

@Configuration
@EnableWebSecurity
class SecurityConfig {
    @Bean
    SecurityFilterChain security(HttpSecurity http) throws Exception {
        return http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/", "/login", "/css/**").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .formLogin(Customizer.withDefaults())
            .build();
    }
}

Common trap: describing extends WebSecurityConfigurerAdapter. It was deprecated in 5.7, and removed in Spring Security 6 (Spring Boot 3).

Key points to cover:

  • MVC-specific integration: @AuthenticationPrincipal injects the current user into controller methods, and the security context is available to views.

Q7. What are the common challenges in securing a Spring MVC application?

Short answer:

  • 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.
  • Secure secret storage.
  • Correct CORS settings.
  • Keeping dependencies patched.
  • Securing Actuator endpoints.
  • Avoiding sensitive data in logs and error responses.

Key points to cover:

  • Deny by default (anyRequest().authenticated()), and test the security rules with spring-security-test (@WithMockUser).

Q8. How do you configure method-level security?

Short answer: 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.
@Configuration
@EnableMethodSecurity                       // replaces @EnableGlobalMethodSecurity(prePostEnabled = true)
class MethodSecurityConfig { }

@Service
class InvoiceService {
    @PreAuthorize("hasRole('ACCOUNTANT') or #customerId == authentication.principal.customerId")
    public List<Invoice> invoicesFor(long customerId) { … }
}

Key points to cover:

  • Method security is enforced by proxies, so self-invocation inside the same class bypasses it, just like @Transactional.

Learn it in depth → Role-Based Access Control

Q9. What does dependency injection mean in the context of Spring MVC?

Short answer: Controllers, services, repositories, interceptors and advice classes are all Spring beans. The container supplies each one's collaborators, instead of the classes creating them. Controllers stay thin, delegating to injected services, which delegate to injected repositories.

Learn it in depth → Spring Dependency Injection

Q10. How does Spring MVC use dependency injection with controllers?

Short answer: Controllers are discovered by component scanning (@Controller/@RestController), and created as singletons. Their dependencies are injected, preferably through a constructor. Separately, method-level injection of request data (@PathVariable, @RequestBody, Principal, Locale) is handled by argument resolvers on every request.

@RestController
class CartController {
    private final CartService carts;                      // constructor-injected once
    CartController(CartService carts) { this.carts = carts; }

    @PostMapping("/cart/items")
    CartDto add(@AuthenticationPrincipal UserDetails user,  // resolved per request
                @Valid @RequestBody AddItem req) {
        return carts.add(user.getUsername(), req);
    }
}

Q11. What types of dependency injection does Spring support?

Short answer: Constructor, setter and field injection. Use constructor injection for required dependencies, and setter injection for optional ones. Avoid field injection in production code: it hides dependencies, prevents final fields, and makes tests depend on Spring or reflection.

Common trap: "field injection is good for optional dependencies". For optional dependencies, use ObjectProvider<T>, Optional<T>, or a setter.

Q12. What are the benefits of dependency injection in web applications?

Short answer:

  • 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: transactions, security, caching.

Follow-up questions this topic invites — and their answers

Q: What's the difference between @ControllerAdvice and @RestControllerAdvice? A: @RestControllerAdvice = @ControllerAdvice + @ResponseBody, so handler return values are written as the response body (JSON). Use it for APIs.

Q: Which HTTP status should an authentication failure return, and which an authorisation failure? A: 401 Unauthorized means "who are you?": missing or invalid credentials. 403 Forbidden means "I know who you are, but you're not allowed".

Q: Does @ExceptionHandler catch exceptions thrown in filters? A: No. Filters run before the DispatcherServlet. Handle those errors in the filter itself, or through Spring Security's AuthenticationEntryPoint and AccessDeniedHandler.

Q: How do you test that an endpoint is secured? A: With @WebMvcTest plus spring-security-test. Call without authentication and expect 401, use @WithMockUser(roles = "USER") and expect 403 on admin paths, and use @WithMockUser(roles = "ADMIN") and expect 200.

Previous

Spring MVC Forms, Views & Interceptors — Interview Questions

Next

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

AI Tutor

Lesson: Spring MVC Exceptions, Security & Dependency Injection — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.