Definition
- Spring MVC is the web module of Spring Framework that handles HTTP requests and responses using the Model-View-Controller pattern.
- DispatcherServlet is the front controller that receives every incoming request and dispatches it to the correct handler method.
- @RestController marks a class as an HTTP endpoint where every method returns data serialized as JSON or XML instead of a view name.
- @Service marks a class that contains business logic, transaction boundaries, and domain rules.
- @Repository marks a data access class. Spring adds automatic translation of database-specific exceptions into Spring's DataAccessException hierarchy.
Think of a National Bank of India branch. The receptionist (DispatcherServlet) greets every customer and directs them to the right counter. The counter clerk (controller) takes the request and fills out the form. The bank officer (service) checks the rules, verifies the account, and approves or rejects the transaction. The vault operator (repository) physically moves the money or updates the ledger. No one does another person's job. The receptionist never touches money, and the vault operator never talks to customers.
Understanding the Concepts
What is Spring MVC?
Spring MVC is the web framework within Spring that handles HTTP requests and responses. It follows the Model-View-Controller pattern where a central servlet called DispatcherServlet receives every incoming HTTP request, finds the matching controller method, calls it, and sends the response back to the client.
In a REST API, you typically use @RestController instead of @Controller. The difference is that @RestController automatically serializes return values to JSON (or XML) without needing a separate view resolver.
package com.bank.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class HealthController {
@GetMapping("/health")
public String health() {
return "National Bank of India API is running";
}
}
GET /api/health
HTTP 200 OK
"National Bank of India API is running"
How does the request-response flow work in Spring MVC?
When a client sends an HTTP request to a Spring Boot application, the request travels through a well-defined pipeline.
- The request arrives at the embedded Tomcat server.
- Servlet filters run first (security, CORS, logging).
- DispatcherServlet receives the request.
- HandlerMapping finds the controller method that matches the URL and HTTP method.
- HandlerAdapter calls the controller method, converting path variables, request parameters, and the request body.
- The controller calls the service layer, which calls the repository layer.
- The return value is passed to an HttpMessageConverter (usually Jackson for JSON).
- The serialized response is sent back to the client.
package com.bank.controller;
import com.bank.dto.AccountResponse;
import com.bank.service.AccountService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/accounts")
public class AccountController {
private final AccountService accountService;
public AccountController(AccountService accountService) {
this.accountService = accountService;
}
@GetMapping("/{accountId}")
public ResponseEntity<AccountResponse> getAccount(
@PathVariable String accountId) {
AccountResponse response = accountService.findAccount(accountId);
return ResponseEntity.ok(response);
}
}
GET /api/accounts/SAV2001
HTTP 200 OK
{
"accountId": "SAV2001",
"holderName": "Rajesh Kumar",
"balance": 75000.00,
"type": "SAVINGS"
}
What is the controller layer?
The controller layer is the entry point for HTTP traffic. It is responsible for:
- Mapping URLs to handler methods using
@GetMapping,@PostMapping,@PutMapping,@DeleteMapping. - Extracting data from the request:
@PathVariable,@RequestParam,@RequestBody,@RequestHeader. - Calling the service layer with domain objects, not HTTP objects.
- Setting the response status code and headers.
- Never containing business logic.
The controller translates HTTP into method calls and method return values back into HTTP.
package com.bank.controller;
import com.bank.dto.AccountResponse;
import com.bank.dto.CreateAccountRequest;
import com.bank.dto.TransferRequest;
import com.bank.dto.TransferResponse;
import com.bank.service.AccountService;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/accounts")
public class AccountController {
private final AccountService accountService;
public AccountController(AccountService accountService) {
this.accountService = accountService;
}
@GetMapping
public List<AccountResponse> listAccounts() {
return accountService.findAllAccounts();
}
@GetMapping("/{accountId}")
public ResponseEntity<AccountResponse> getAccount(
@PathVariable String accountId) {
AccountResponse account = accountService.findAccount(accountId);
return ResponseEntity.ok(account);
}
@PostMapping
public ResponseEntity<AccountResponse> createAccount(
@Valid @RequestBody CreateAccountRequest request) {
AccountResponse created = accountService.createAccount(request);
return ResponseEntity.status(HttpStatus.CREATED).body(created);
}
@PostMapping("/{accountId}/transfer")
public ResponseEntity<TransferResponse> transfer(
@PathVariable String accountId,
@Valid @RequestBody TransferRequest request) {
TransferResponse result = accountService.transfer(
accountId, request);
return ResponseEntity.ok(result);
}
@DeleteMapping("/{accountId}")
public ResponseEntity<Void> closeAccount(
@PathVariable String accountId) {
accountService.closeAccount(accountId);
return ResponseEntity.noContent().build();
}
}
POST /api/accounts
{"holderName":"Priya Sharma","type":"SAVINGS","initialDeposit":25000.00}
HTTP 201 Created
{"accountId":"SAV2003","holderName":"Priya Sharma","balance":25000.00,"type":"SAVINGS"}
What is the service layer?
The service layer contains all business logic. It enforces rules, coordinates operations across multiple repositories, and defines transaction boundaries. The service layer does not know anything about HTTP. It receives plain Java objects and returns plain Java objects.
package com.bank.service;
import com.bank.dto.AccountResponse;
import com.bank.dto.CreateAccountRequest;
import com.bank.dto.TransferRequest;
import com.bank.dto.TransferResponse;
import com.bank.exception.AccountNotFoundException;
import com.bank.exception.InsufficientFundsException;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.List;
@Service
public class AccountService {
private static final BigDecimal MINIMUM_BALANCE =
new BigDecimal("1000.00");
private final AccountRepository accountRepository;
public AccountService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
public List<AccountResponse> findAllAccounts() {
return accountRepository.findAll().stream()
.map(this::toResponse)
.toList();
}
public AccountResponse findAccount(String accountId) {
Account account = accountRepository.findById(accountId)
.orElseThrow(() -> new AccountNotFoundException(
"Account not found: " + accountId));
return toResponse(account);
}
@Transactional
public AccountResponse createAccount(CreateAccountRequest request) {
Account account = new Account();
account.setHolderName(request.holderName());
account.setType(request.type());
account.setBalance(request.initialDeposit());
Account saved = accountRepository.save(account);
return toResponse(saved);
}
@Transactional
public TransferResponse transfer(
String fromAccountId, TransferRequest request) {
Account from = accountRepository.findById(fromAccountId)
.orElseThrow(() -> new AccountNotFoundException(
"Source account not found: " + fromAccountId));
Account to = accountRepository.findById(request.toAccountId())
.orElseThrow(() -> new AccountNotFoundException(
"Target account not found: " + request.toAccountId()));
BigDecimal amount = request.amount();
BigDecimal remainingBalance = from.getBalance().subtract(amount);
if (remainingBalance.compareTo(MINIMUM_BALANCE) < 0) {
throw new InsufficientFundsException(
"Transfer would leave balance below minimum: "
+ MINIMUM_BALANCE);
}
from.setBalance(remainingBalance);
to.setBalance(to.getBalance().add(amount));
accountRepository.save(from);
accountRepository.save(to);
return new TransferResponse(
fromAccountId, request.toAccountId(),
amount, from.getBalance());
}
@Transactional
public void closeAccount(String accountId) {
Account account = accountRepository.findById(accountId)
.orElseThrow(() -> new AccountNotFoundException(
"Account not found: " + accountId));
if (account.getBalance().compareTo(BigDecimal.ZERO) > 0) {
throw new IllegalStateException(
"Cannot close account with positive balance: "
+ account.getBalance());
}
accountRepository.delete(account);
}
private AccountResponse toResponse(Account account) {
return new AccountResponse(
account.getAccountId(),
account.getHolderName(),
account.getBalance(),
account.getType());
}
}
// Transfer: Rajesh sends 10000 to Priya
POST /api/accounts/SAV2001/transfer
{"toAccountId":"SAV2002","amount":10000.00}
HTTP 200 OK
{"fromAccountId":"SAV2001","toAccountId":"SAV2002","amount":10000.00,"remainingBalance":65000.00}
What is the repository layer?
The repository layer handles all data access. In Spring Data JPA, you extend JpaRepository and Spring generates the implementation at runtime. The @Repository annotation also enables automatic exception translation: database-specific exceptions (like SQLException) are translated into Spring's DataAccessException hierarchy.
package com.bank.repository;
import com.bank.model.Account;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
@Repository
public interface AccountRepository extends JpaRepository<Account, String> {
List<Account> findByType(String type);
List<Account> findByHolderNameContainingIgnoreCase(String name);
@Query("SELECT a FROM Account a WHERE a.balance >= :minBalance")
List<Account> findAccountsAboveBalance(BigDecimal minBalance);
Optional<Account> findByAccountId(String accountId);
}
package com.bank.model;
import jakarta.persistence.*;
import java.math.BigDecimal;
@Entity
@Table(name = "accounts")
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
@Column(name = "account_id")
private String accountId;
@Column(name = "holder_name", nullable = false)
private String holderName;
@Column(name = "balance", nullable = false, precision = 15, scale = 2)
private BigDecimal balance;
@Column(name = "type", nullable = false)
private String type;
// Getters and setters
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
public String getHolderName() { return holderName; }
public void setHolderName(String holderName) { this.holderName = holderName; }
public BigDecimal getBalance() { return balance; }
public void setBalance(BigDecimal balance) { this.balance = balance; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
}
// Spring Data JPA generates this SQL at runtime:
SELECT a.account_id, a.holder_name, a.balance, a.type
FROM accounts a
WHERE a.account_id = 'SAV2001'
How do DTOs connect the layers?
Data Transfer Objects (DTOs) carry data between the controller and service layers. They prevent exposing JPA entities directly in the API response, which would leak database details and create tight coupling between the database schema and the API contract.
package com.bank.dto;
import java.math.BigDecimal;
public record AccountResponse(
String accountId,
String holderName,
BigDecimal balance,
String type
) {}
package com.bank.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;
import java.math.BigDecimal;
public record CreateAccountRequest(
@NotBlank String holderName,
@NotBlank String type,
@Positive BigDecimal initialDeposit
) {}
package com.bank.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;
import java.math.BigDecimal;
public record TransferRequest(
@NotBlank String toAccountId,
@Positive BigDecimal amount
) {}
package com.bank.dto;
import java.math.BigDecimal;
public record TransferResponse(
String fromAccountId,
String toAccountId,
BigDecimal amount,
BigDecimal remainingBalance
) {}
// The controller receives CreateAccountRequest (DTO)
// The service maps it to Account (entity)
// The repository saves the entity
// The service maps the entity back to AccountResponse (DTO)
// The controller returns the DTO as JSON
How is Spring MVC different from Spring WebFlux?
Spring MVC is the traditional blocking, thread-per-request model. Spring WebFlux is the reactive, non-blocking model.
| Feature | Spring MVC | Spring WebFlux |
|---|---|---|
| Programming model | Blocking, imperative | Non-blocking, reactive |
| Return types | ResponseEntity, POJO | Mono, Flux |
| Thread model | One thread per request | Event loop with few threads |
| Server | Tomcat, Jetty | Netty, Tomcat, Jetty |
| Backpressure | No | Yes (Reactive Streams) |
| JDBC/JPA support | Full | Requires R2DBC |
| Learning curve | Lower | Higher |
| Best for | CRUD APIs, most banking apps | High-concurrency streaming |
// Spring MVC: blocking, familiar
@GetMapping("/{accountId}")
public ResponseEntity<AccountResponse> getAccount(
@PathVariable String accountId) {
AccountResponse response = accountService.findAccount(accountId);
return ResponseEntity.ok(response);
}
// Spring WebFlux: non-blocking, reactive
@GetMapping("/{accountId}")
public Mono<ResponseEntity<AccountResponse>> getAccount(
@PathVariable String accountId) {
return accountService.findAccount(accountId)
.map(ResponseEntity::ok);
}
For a banking CRUD API, Spring MVC is the right choice.
It is simpler, works with JPA and JDBC, and virtual threads
in Java 25 with Spring Boot 3.4 eliminate the thread-per-request
scalability concern.
What about exception handling across layers?
Use @RestControllerAdvice to catch exceptions from any controller and return consistent error responses. This keeps error formatting out of individual controllers.
package com.bank.exception;
public class AccountNotFoundException extends RuntimeException {
public AccountNotFoundException(String message) {
super(message);
}
}
package com.bank.exception;
public class InsufficientFundsException extends RuntimeException {
public InsufficientFundsException(String message) {
super(message);
}
}
package com.bank.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(AccountNotFoundException.class)
public ProblemDetail handleNotFound(AccountNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Account Not Found");
return problem;
}
@ExceptionHandler(InsufficientFundsException.class)
public ProblemDetail handleInsufficientFunds(
InsufficientFundsException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.UNPROCESSABLE_ENTITY, ex.getMessage());
problem.setTitle("Insufficient Funds");
return problem;
}
@ExceptionHandler(Exception.class)
public ProblemDetail handleGeneral(Exception ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.INTERNAL_SERVER_ERROR,
"An unexpected error occurred");
problem.setTitle("Internal Server Error");
return problem;
}
}
GET /api/accounts/INVALID999
HTTP 404 Not Found
{
"type": "about:blank",
"title": "Account Not Found",
"status": 404,
"detail": "Account not found: INVALID999"
}
What are common mistakes in layered architecture?
Mistake 1: Business logic in the controller
WRONG: The controller checks the minimum balance.
@PostMapping("/{accountId}/transfer")
public ResponseEntity<TransferResponse> transfer(
@PathVariable String accountId,
@RequestBody TransferRequest request) {
// WRONG: Business logic in the controller
Account from = accountRepository.findById(accountId).orElseThrow();
if (from.getBalance().subtract(request.amount())
.compareTo(new BigDecimal("1000.00")) < 0) {
throw new InsufficientFundsException("Not enough funds");
}
// ... direct repository calls from controller
}
CORRECT: The controller delegates to the service.
@PostMapping("/{accountId}/transfer")
public ResponseEntity<TransferResponse> transfer(
@PathVariable String accountId,
@RequestBody TransferRequest request) {
// CORRECT: Controller only delegates, service has the logic
TransferResponse result = accountService.transfer(
accountId, request);
return ResponseEntity.ok(result);
}
Mistake 2: Returning JPA entities directly
WRONG: Returning the entity from the controller.
@GetMapping("/{accountId}")
public Account getAccount(@PathVariable String accountId) {
// WRONG: Exposes JPA entity, including internal fields,
// lazy-loading proxies, and circular references
return accountRepository.findById(accountId).orElseThrow();
}
CORRECT: Map to a DTO.
@GetMapping("/{accountId}")
public ResponseEntity<AccountResponse> getAccount(
@PathVariable String accountId) {
// CORRECT: Return a DTO, decoupled from the database schema
AccountResponse response = accountService.findAccount(accountId);
return ResponseEntity.ok(response);
}
What should a senior or principal engineer know?
- Transaction boundaries belong in the service layer. The @Transactional annotation on service methods ensures that all repository calls within a single business operation either commit together or roll back together. Never place @Transactional on controllers or repositories.
- Spring Boot 3.4 with virtual threads. Setting spring.threads.virtual.enabled=true means each HTTP request runs on a virtual thread. This eliminates the need for reactive programming in most banking APIs. You keep the familiar blocking model (Spring MVC + JPA) but handle thousands of concurrent requests without running out of platform threads.
- CQRS in the service layer. For high-traffic banking systems, separate the read and write service methods. Use @Transactional(readOnly = true) for queries, which allows Spring to optimize the JPA flush mode and JDBC connection settings.
- Hexagonal architecture. In complex domains, the service layer should depend on interfaces (ports), not concrete repositories. This allows you to swap the persistence mechanism (JPA to JDBC, or JDBC to MongoDB) without changing business logic.
- Integration testing the layers. Use @WebMvcTest to test controllers in isolation (no service or repository beans). Use @DataJpaTest to test repositories with an embedded database. Use @SpringBootTest for full integration tests.
package com.bank;
import com.bank.controller.AccountController;
import com.bank.service.AccountService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.bean.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(AccountController.class)
class AccountControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private AccountService accountService;
@Test
void shouldReturnAccount() throws Exception {
// given
var response = new com.bank.dto.AccountResponse(
"SAV2001", "Rajesh Kumar",
new java.math.BigDecimal("75000.00"), "SAVINGS");
org.mockito.Mockito.when(
accountService.findAccount("SAV2001"))
.thenReturn(response);
// when + then
mockMvc.perform(get("/api/accounts/SAV2001"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.accountId").value("SAV2001"))
.andExpect(jsonPath("$.holderName").value("Rajesh Kumar"))
.andExpect(jsonPath("$.balance").value(75000.00));
}
}
AccountControllerTest > shouldReturnAccount() PASSED
What are common interview follow-up questions?
- What is the difference between
@Controllerand@RestController? - How does
@RequestBodydeserialization work under the hood? - What is the difference between
@PathVariableand@RequestParam? - How does
@Validateddiffer from@Validfor request validation? - What happens if two controllers have the same
@RequestMapping? - How do you test a controller without starting the full application context?
- What is the purpose of
@Transactional(readOnly = true)on a read service method? - How does Spring Data JPA generate query implementations from method names?
- When would you use
@Queryover derived query methods? - How do you handle pagination in the controller layer?
Visual Overview
HTTP Request
|
v
+---------------------------+
| Servlet Filters |
| (Security, CORS, Logging)|
+---------------------------+
|
v
+---------------------------+
| DispatcherServlet |
| (Front Controller) |
+---------------------------+
|
v
+---------------------------+
| HandlerMapping |
| Finds matching method |
+---------------------------+
|
v
+--------------------------------------------+
| Controller (@RestController) |
| HTTP concerns: @GetMapping, @PathVariable |
| Delegates to service layer |
+--------------------------------------------+
|
v
+--------------------------------------------+
| Service (@Service) |
| Business logic: validation, rules, @Tx |
| Calls repository layer |
+--------------------------------------------+
|
v
+--------------------------------------------+
| Repository (@Repository) |
| Data access: JPA, JDBC, findById, save |
| Returns entities |
+--------------------------------------------+
|
v
+---------------------------+
| Database |
+---------------------------+
Project Structure
=================
com.bank/
BankApplication.java
controller/
AccountController.java
service/
AccountService.java
repository/
AccountRepository.java
model/
Account.java
dto/
AccountResponse.java
CreateAccountRequest.java
TransferRequest.java
TransferResponse.java
exception/
AccountNotFoundException.java
InsufficientFundsException.java
GlobalExceptionHandler.java
Key Takeaway
Spring MVC organizes a web application into three clean layers, and each layer has exactly one job. The controller layer handles HTTP: it maps URLs to methods, extracts path variables and request bodies, and sets response status codes. It never contains business logic. The service layer enforces business rules, coordinates operations, and defines transaction boundaries. It never knows about HTTP. The repository layer handles data access using Spring Data JPA, and its methods either return entities or throw exceptions that Spring translates automatically.
The layers connect through constructor injection. The controller depends on the service interface, and the service depends on the repository interface. This makes every layer independently testable. You can test the controller with @WebMvcTest and a mocked service, test the service with a mocked repository, and test the repository with @DataJpaTest and an embedded database.
DTO records carry data between the controller and service layers. They prevent JPA entities from leaking into the API response, which would create tight coupling between the database schema and the HTTP contract. When the database schema changes, only the mapping code changes. The API consumers see a stable contract.
For a banking application at National Bank of India, this architecture handles account lookups, transfers, and balance checks cleanly. Business rules like minimum balance enforcement live in the service layer. HTTP concerns like status codes live in the controller. Database queries live in the repository. Exception handling is centralized in a @RestControllerAdvice that converts exceptions to RFC 7807 ProblemDetail responses.
Remember one sentence: controllers translate HTTP, services enforce rules, and repositories persist data.
---