Project Setup & Layered Architecture
Spring Initializr, JAR vs WAR, Controller/Service/Repository layers, DTOs and request flow
- Bootstrap a Spring Boot project from Spring Initializr
- Apply the 3-layer architecture pattern
- Trace a complete HTTP request through Controller → Service → Repository
A professional-quality reference covering Spring Boot project setup from scratch, JAR vs WAR packaging, the layered architecture pattern, DTOs, entities, and a full end-to-end request flow walkthrough.
Table of Contents
- What is Spring Boot?
- Setting Up a Spring Boot Project
- JAR vs WAR — Packaging Types
- Project Structure After Setup
- Layered Architecture in Spring Boot
- Layer 1 — Controller Layer
- Layer 2 — Service Layer
- Layer 3 — Repository Layer
- Supporting Package — DTO (Data Transfer Object)
- Supporting Package — Entity
- Supporting Package — Utility
- Supporting Package — Configuration
- End-to-End Request Flow Walkthrough
- Maven
pom.xml— Dependency Management - Quick Reference Table
- Interview Notes
- Common Mistakes
- Best Practices
- Practice Questions
- Summary
1. What is Spring Boot?
Overview
Spring Boot is a framework built on top of the Spring Framework that simplifies the creation of production-ready, standalone Java applications. It eliminates most of the boilerplate configuration traditionally required in Spring by providing:
- Auto-configuration — Spring Boot detects what libraries are on the classpath and configures them automatically
- Embedded server — An embedded Tomcat (or Jetty/Undertow) server is bundled inside the application itself; no separate server installation required
- Starter dependencies — Curated dependency bundles (e.g.,
spring-boot-starter-web) that pull in everything needed for a feature - Production-ready defaults — Sensible configuration out of the box
Why Spring Boot Exists
Before Spring Boot, setting up a Spring application required:
- Writing extensive XML configuration files
- Deploying a WAR file to an external application server
- Manually managing dependency version compatibility
Spring Boot solves all three problems: convention over configuration, embedded server, and managed dependency versions.
2. Setting Up a Spring Boot Project
Method 1 Spring Initializr (Recommended, Works for All IDEs)
The official Spring Initializr website generates a ready-to-import project skeleton.
Step-by-Step Setup
Step 1 — Choose Project Type (Build Tool)
| Option | Description |
|---|---|
| Maven | XML-based build and dependency management; most widely used in enterprise Java |
| Gradle | Groovy/Kotlin DSL-based; popular in Android and modern Java projects |
For beginners and most enterprise projects, Maven is the standard choice.
Step 2 — Choose Language
Select Java (Kotlin and Groovy are also options).
Step 3 — Choose Spring Boot Version
Pick the latest stable release (e.g., 3.2.3). Avoid SNAPSHOT versions in production — they are development builds and may be unstable.
Step 4 — Fill Project Metadata
| Field | Purpose | Example |
|---|---|---|
| Group | Uniquely identifies your organisation — typically a reversed domain name | com.conceptandcoding |
| Artifact | The project/module name | learning-spring-boot |
| Name | Display name of the project | Learning Spring Boot |
| Description | Short description | Demo project for Spring Boot |
| Package Name | Auto-generated from Group + Artifact | com.conceptandcoding.learningspringboot |
Together, Group + Artifact uniquely identify a project in the Maven ecosystem — similar to how a full class name (package + class) uniquely identifies a Java class.
Step 5 — Choose Packaging
Select JAR for modern microservices (explained in detail in section 3).
Step 6 — Choose Java Version
Select the Java version your team uses. Common stable choices:
- Java 17 — LTS (Long-Term Support), widely used in industry
- Java 21 — Latest LTS
Step 7 — Add Dependencies
For a basic web application / REST API, add:
| Dependency | What it provides |
|---|---|
| Spring Web | Builds RESTful web APIs; includes embedded Tomcat server; provides @RestController, @GetMapping, etc. |
You can add more dependencies later directly in pom.xml. Start minimal and grow as needed.
Step 8 — Generate and Download
Click Generate. A .zip file is downloaded to your system containing the complete project skeleton.
Step 9 — Open in IDE
- Extract the
.zipfile - Open your IDE (IntelliJ IDEA, Eclipse, VS Code)
- Import the project as a Maven project
In IntelliJ: File → Open → select the extracted folder
Method 2 IntelliJ IDEA Ultimate (Direct IDE Setup)
IntelliJ IDEA Ultimate has Spring Initializr built in:
File → New → Project- Select Spring from the left panel
- Fill in the same metadata fields as above
- Choose dependencies
- Click Finish
What You Get After Setup
After opening the project, you will find exactly two things:
1src/2└── main/3 └── java/4 └── com/conceptandcoding/learningspringboot/5 └── LearningSpringBootApplication.java ← Main application class6pom.xml ← Maven dependency fileLearningSpringBootApplication.java — The entry point:
1package com.conceptandcoding.learningspringboot;2
3import org.springframework.boot.SpringApplication;4import org.springframework.boot.autoconfigure.SpringBootApplication;5
6@SpringBootApplication7public class LearningSpringBootApplication {8 public static void main(String[] args) {9 SpringApplication.run(LearningSpringBootApplication.class, args);10 }11}Running this class starts the embedded Tomcat server. If you run it immediately after setup (before writing any controllers), you will see in the console:
1Tomcat started on port(s): 8080 (http)2Started LearningSpringBootApplication in 2.345 secondsThe server is running, but since no endpoints are defined yet, no API can be called yet.
3. JAR vs WAR Packaging Types
Definition
| Term | Full Form | Purpose |
|---|---|---|
| JAR | Java ARchive | Packages a standalone Java application with all its dependencies |
| WAR | Web ARchive | Packages a complete web application including HTML, CSS, JavaScript, JSP pages, for deployment to an external server |
Detailed Comparison
| Aspect | JAR | WAR |
|---|---|---|
| Contains | Java classes + libraries + resources | Java classes + web resources (HTML/CSS/JS/JSP) + libraries |
| Server | Embedded (Tomcat bundled inside) | External (deploy to Tomcat, JBoss, WebLogic, etc.) |
| Deployment | Run with java -jar app.jar | Drop .war file into server's webapps/ folder |
| Use case | Microservices, REST APIs, standalone apps | Traditional monolithic web apps with server-rendered pages |
| Modern usage | ✅ Standard in microservices era | ⚠️ Legacy — used before microservices |
Real-World Context
In the microservices architecture that dominates modern software:
- Each service is an independent, self-contained application
- It starts its own server, listens on a port, and handles requests
- It does not need HTML, CSS, or JavaScript bundled with it — the frontend is a separate application
- JAR is the correct choice for every microservice
WAR was common in the era of monolithic applications where one server hosted the entire application (backend logic + HTML pages + CSS). That architecture is largely obsolete in new projects.
Diagram
4. Project Structure After Setup
A well-organised Spring Boot project following layered architecture looks like this:
1src/2└── main/3 ├── java/4 │ └── com/conceptandcoding/learningspringboot/5 │ ├── LearningSpringBootApplication.java ← Entry point6 │ ├── controller/ ← Controller layer7 │ │ └── PaymentController.java8 │ ├── service/ ← Service layer9 │ │ └── PaymentService.java10 │ ├── repository/ ← Repository layer11 │ │ └── PaymentRepository.java12 │ ├── dto/ ← Data Transfer Objects13 │ │ ├── PaymentRequest.java14 │ │ └── PaymentResponse.java15 │ ├── entity/ ← DB table representations16 │ │ └── PaymentEntity.java17 │ ├── utility/ ← Helper/common methods18 │ │ └── PaymentUtil.java19 │ └── config/ ← Configuration classes20 │ └── AppConfig.java21 └── resources/22 └── application.properties ← External configuration23pom.xml ← Maven dependencies5. Layered Architecture in Spring Boot
Overview
The layered architecture (also called the n-tier architecture) is the standard architectural pattern used in Spring Boot applications across the industry. It organises your code into distinct horizontal layers, each with a clear and specific responsibility.
Why Layered Architecture?
| Problem without layers | How layered architecture solves it |
|---|---|
| Business logic scattered everywhere | Service layer is the designated home for all business logic |
| DB code mixed with API handling code | Repository layer exclusively handles DB operations |
| Any change in external API schema breaks internal code | Controller layer absorbs schema changes via DTO mapping |
| Hard to test individual components | Each layer can be unit-tested independently |
| Hard to onboard new developers | Standard structure — any experienced Java developer knows where to look |
The Three Core Layers
One-Line Summary of Each Layer
| Layer | Annotation | Responsibility |
|---|---|---|
| Controller | @RestController / @Controller | Receives requests, sends responses, does DTO mapping |
| Service | @Service | Contains all business logic |
| Repository | @Repository | Connects to and queries the database |
6. Layer 1 Controller Layer
Overview
The Controller layer is the entry point of your application for every incoming HTTP request. It is the outermost layer — the only layer that directly communicates with the outside world (clients, browsers, mobile apps, other services).
Responsibilities
- Host API endpoints — declare the URL paths and HTTP methods (
GET,POST,PUT,DELETE) - Receive request data — extract parameters, request bodies, headers
- Map incoming data to Request DTOs — translate external data formats into internal DTOs
- Delegate to Service layer — never contain business logic itself
- Receive Response DTOs from Service layer
- Return HTTP responses to the client
Key Annotations
| Annotation | Purpose |
|---|---|
@RestController | Marks class as a REST controller; combines @Controller + @ResponseBody (returns JSON by default) |
@Controller | Classic controller; typically used for server-rendered views (Thymeleaf, JSP) |
@GetMapping("/path") | Maps HTTP GET requests to this method |
@PostMapping("/path") | Maps HTTP POST requests to this method |
@RequestBody | Binds the HTTP request body to a method parameter |
@PathVariable | Extracts a variable from the URL path |
@RequestParam | Extracts a query parameter from the URL |
Code Example
1package com.conceptandcoding.learningspringboot.controller;2
3import com.conceptandcoding.learningspringboot.dto.PaymentRequest;4import com.conceptandcoding.learningspringboot.dto.PaymentResponse;5import com.conceptandcoding.learningspringboot.service.PaymentService;6import org.springframework.beans.factory.annotation.Autowired;7import org.springframework.web.bind.annotation.*;8
9@RestController10@RequestMapping("/payment")11public class PaymentController {12
13 @Autowired14 private PaymentService paymentService;15
16 @GetMapping("/{id}")17 public PaymentResponse getPaymentDetails(@PathVariable String id) {18 // Step 1: Map incoming request data to internal DTO19 PaymentRequest paymentRequest = new PaymentRequest();20 paymentRequest.setPaymentId(id);21
22 // Step 2: Delegate to Service layer23 PaymentResponse response = paymentService.getPaymentDetails(paymentRequest);24
25 // Step 3: Return response to client26 return response;27 }28}Line-by-Line Explanation
| Line | Explanation |
|---|---|
@RestController | Spring registers this class as a REST controller; all methods return JSON by default |
@RequestMapping("/payment") | All endpoints in this class are prefixed with /payment |
@Autowired PaymentService | Spring injects a PaymentService bean automatically |
@GetMapping("/{id}") | Maps GET /payment/{id} to this method |
@PathVariable String id | Extracts the {id} segment from the URL |
PaymentRequest paymentRequest = new PaymentRequest() | Creates internal DTO |
paymentRequest.setPaymentId(id) | Maps external field to internal DTO — this is the mapping responsibility |
paymentService.getPaymentDetails(paymentRequest) | Delegates to Service — controller does NOT perform business logic |
What Controller Should NOT Do
1// ❌ Business logic in controller — wrong!2@GetMapping("/{id}")3public PaymentResponse getPaymentDetails(@PathVariable String id) {4 // Never calculate, transform, or make decisions here5 double tax = amount * 0.18; // ❌ Business logic belongs in Service6 return response;7}7. Layer 2 Service Layer
Overview
The Service layer is the heart of your application. It contains all business logic — the rules, calculations, decisions, and transformations that define what your application does.
Responsibilities
- Contain all business logic
- Coordinate calls between multiple repositories if needed
- Map Entity objects (from repository) to Response DTOs (for controller)
- Apply validations, transformations, business rules
- Call external APIs if required
Key Annotation
| Annotation | Purpose |
|---|---|
@Service | Marks the class as a Spring service bean; Spring manages its lifecycle |
Code Example
1package com.conceptandcoding.learningspringboot.service;2
3import com.conceptandcoding.learningspringboot.dto.PaymentRequest;4import com.conceptandcoding.learningspringboot.dto.PaymentResponse;5import com.conceptandcoding.learningspringboot.entity.PaymentEntity;6import com.conceptandcoding.learningspringboot.repository.PaymentRepository;7import org.springframework.beans.factory.annotation.Autowired;8import org.springframework.stereotype.Service;9
10@Service11public class PaymentService {12
13 @Autowired14 private PaymentRepository paymentRepository;15
16 public PaymentResponse getPaymentDetails(PaymentRequest paymentRequest) {17 // Step 1: Call repository to fetch data (comes back as Entity)18 PaymentEntity paymentEntity = paymentRepository.getPaymentById(paymentRequest);19
20 // Step 2: Map Entity → Response DTO (keep DB column names internal)21 PaymentResponse response = new PaymentResponse();22 response.setPaymentId(paymentEntity.getPaymentId());23 response.setAmount(paymentEntity.getPaymentAmount()); // field name differs from DB column24 response.setCurrency(paymentEntity.getPaymentCurrency());25
26 // Step 3: Return Response DTO to controller27 return response;28 }29}Why the Service Layer Maps Entity to Response DTO
The database table may have a column named payment_amount. The Response DTO field that goes to the client is named amount. The Service layer owns this mapping — so if the DB column name changes, only the Service layer needs updating. The controller and the client-facing DTO are unaffected.
8. Layer 3 Repository Layer
Overview
The Repository layer is the only layer that should directly communicate with the database. It is responsible for all data access operations: fetching, inserting, updating, and deleting records.
Responsibilities
- Execute database queries (SQL / JPQL / NoSQL)
- Return results as Entity objects
- Receive Entity objects for insert/update operations
- Isolate all DB interaction from the rest of the application
Key Annotation
| Annotation | Purpose |
|---|---|
@Repository | Marks the class as a data access bean; Spring also translates DB-specific exceptions into Spring's unified exception hierarchy |
Code Example
1package com.conceptandcoding.learningspringboot.repository;2
3import com.conceptandcoding.learningspringboot.dto.PaymentRequest;4import com.conceptandcoding.learningspringboot.entity.PaymentEntity;5import org.springframework.stereotype.Repository;6
7@Repository8public class PaymentRepository {9
10 public PaymentEntity getPaymentById(PaymentRequest paymentRequest) {11 // In real projects: use Spring Data JPA, JDBC Template, etc.12 // For this example: simulating a DB fetch13 PaymentEntity entity = new PaymentEntity();14 entity.setPaymentId(paymentRequest.getPaymentId());15 entity.setPaymentAmount(1000.00);16 entity.setPaymentCurrency("INR");17 return entity;18 }19}JpaRepository) which provide ready-made CRUD methods — no manual SQL needed. Or they use JdbcTemplate for raw SQL. The key principle remains: all DB access lives here.What Repository Should NOT Do
1// ❌ Business logic in repository — wrong!2@Repository3public class PaymentRepository {4 public PaymentEntity getPayment(PaymentRequest req) {5 PaymentEntity entity = fetchFromDB(req.getId());6 entity.setAmount(entity.getAmount() * 1.18); // ❌ Tax calculation — belongs in Service7 return entity;8 }9}9. Supporting Package DTO (Data Transfer Object)
Overview
DTOs are plain Java objects used to carry data between layers or between your application and the outside world. They act as a protective buffer — decoupling your internal data model from what external clients send and receive.
Why DTOs Exist The Problem They Solve
Without DTOs
If your controller directly works with the same field names that clients send:
1// Client sends: { "id": "123", "cardNumber": "54321" }2// Your controller uses 'id' directly everywhere internallyNow if the client schema changes from id to sequenceNumber:
- You must update every class, method, and variable that referenced
id - Changes propagate through controller → service → repository → entity
- High risk of bugs
With DTOs (Request DTO)
- The controller maps
id(external name) topaymentId(internal DTO field) - All other layers work with
paymentIdexclusively - If the client changes to
sequenceNumber, only the controller mapping changes — nothing else is affected
Two Types of DTOs
Request DTO
Carries data from the client into your application.
1package com.conceptandcoding.learningspringboot.dto;2
3public class PaymentRequest {4 private String paymentId; // Internal name — may differ from client's field name5
6 public String getPaymentId() { return paymentId; }7 public void setPaymentId(String paymentId) { this.paymentId = paymentId; }8}Response DTO
Carries data from your application back to the client. It controls exactly which fields are exposed — you never expose DB column names or internal implementation details.
1package com.conceptandcoding.learningspringboot.dto;2
3public class PaymentResponse {4 private String paymentId;5 private Double amount; // 'amount' — not 'payment_amount' (the DB column name)6 private String currency;7
8 // Getters and setters9 public String getPaymentId() { return paymentId; }10 public void setPaymentId(String paymentId) { this.paymentId = paymentId; }11 public Double getAmount() { return amount; }12 public void setAmount(Double amount) { this.amount = amount; }13 public String getCurrency() { return currency; }14 public void setCurrency(String currency) { this.currency = currency; }15}Diagram Where DTOs Are Used
Key Benefits of DTOs
| Benefit | Explanation |
|---|---|
| Schema isolation | External schema changes only impact the mapping point (controller) |
| Security | You choose exactly which fields to expose; DB column names are never leaked |
| Flexibility | Internal and external field names can differ freely |
| Testability | DTOs are simple POJOs — easy to create in tests |
10. Supporting Package Entity
Overview
Entities are Java classes that directly represent database tables. Each field in an entity class corresponds to a column in a database table. The field name should match the column name exactly.
Why Entities Exist
In Java, everything is an object. When you fetch a row from a database, the result must be mapped into a Java object. Entities are those objects. Frameworks like Spring Data JPA and JDBC Template use these entity classes to:
- Automatically map query results to entity objects (rows → fields)
- Automatically generate SQL from entity objects (fields → columns)
Key Annotation
| Annotation | Purpose |
|---|---|
@Entity | Marks the class as a JPA entity — a direct representation of a DB table |
@Table(name = "table_name") | Specifies the exact table name (optional if class name matches) |
@Id | Marks the primary key field |
@Column(name = "col_name") | Maps a field to a specific column name |
Code Example
1package com.conceptandcoding.learningspringboot.entity;2
3import jakarta.persistence.Entity;4import jakarta.persistence.Id;5
6@Entity7public class PaymentEntity {8
9 @Id10 private String paymentId; // corresponds to DB column: payment_id11 private Double paymentAmount; // corresponds to DB column: payment_amount12 private String paymentCurrency; // corresponds to DB column: payment_currency13
14 // Getters and setters15 public String getPaymentId() { return paymentId; }16 public void setPaymentId(String paymentId) { this.paymentId = paymentId; }17 public Double getPaymentAmount() { return paymentAmount; }18 public void setPaymentAmount(Double paymentAmount) { this.paymentAmount = paymentAmount; }19 public String getPaymentCurrency() { return paymentCurrency; }20 public void setPaymentCurrency(String paymentCurrency) { this.paymentCurrency = paymentCurrency; }21}Corresponding Database Table
| DB Column | Entity Field |
|---|---|
payment_id | paymentId |
payment_amount | paymentAmount |
payment_currency | paymentCurrency |
The ORM (Object-Relational Mapping) framework handles the mapping between Java's camelCase convention and SQL's snake_case convention automatically.
Entity vs DTO Critical Distinction
| Aspect | Entity | DTO |
|---|---|---|
| Represents | A database table | Data being transferred |
| Used by | Repository layer | Controller and Service layers |
| Field names match | DB column names | Whatever is convenient / agreed with client |
| Annotation | @Entity | None (plain POJO) |
| Exposed to client? | ❌ Never directly | ✅ Yes (Response DTO) |
11. Supporting Package Utility
Overview
The Utility (or Helper) package contains common methods that are shared across multiple classes in the service or repository layer. These are stateless helper functions that don't belong to any single class's core responsibility.
Characteristics
- Contains static or simple utility methods
- No business logic specific to a single feature
- No DB access
- Examples: date formatting, string manipulation, conversion helpers, mathematical calculations used in multiple places
Code Example
1package com.conceptandcoding.learningspringboot.utility;2
3public class PaymentUtil {4
5 // Common method reused by multiple service classes6 public static String formatCurrency(Double amount, String currency) {7 return currency + " " + String.format("%.2f", amount);8 }9
10 public static boolean isValidPaymentId(String paymentId) {11 return paymentId != null && paymentId.length() == 10;12 }13}Usage in Service layer:
1String formatted = PaymentUtil.formatCurrency(1000.0, "INR"); // "INR 1000.00"When to Create a Utility Method
- The same logic appears in two or more service or repository classes
- The logic is not specific to any one feature or domain
- The method is stateless (doesn't depend on instance variables)
12. Supporting Package Configuration
Overview
The Configuration package manages external configuration values that drive your application's behavior. The core principle: never hardcode values that might change — drive them from configuration files instead.
The Problem with Hardcoded Values
1// ❌ Hardcoded — requires code change + redeployment to modify2int timeout = 5000;3String dbUrl = "jdbc:mysql://localhost:3306/mydb";If timeout needs to change from 5000ms to 10000ms in production, you must:
- Change the code
- Rebuild the project
- Redeploy the application
This is slow, risky, and unnecessary.
The Solution `application.properties`
Store configuration values in src/main/resources/application.properties:
1# application.properties2payment.timeout=50003payment.maxRetries=34server.port=80805spring.datasource.url=jdbc:mysql://localhost:3306/paymentdbReading Configuration in Code
Using `@Value`
1import org.springframework.beans.factory.annotation.Value;2import org.springframework.stereotype.Service;3
4@Service5public class PaymentService {6
7 @Value("${payment.timeout}")8 private int timeout; // Spring reads from application.properties at startup9
10 @Value("${payment.maxRetries}")11 private int maxRetries;12
13 public void processPayment() {14 // Use 'timeout' and 'maxRetries' — no hardcoded values15 }16}Using `@ConfigurationProperties` (for grouped config)
1import org.springframework.boot.context.properties.ConfigurationProperties;2import org.springframework.stereotype.Component;3
4@Component5@ConfigurationProperties(prefix = "payment")6public class PaymentConfig {7 private int timeout;8 private int maxRetries;9
10 // Getters and setters11}The Benefit
To change timeout from 5000 to 10000:
- Edit
application.properties:payment.timeout=10000 - Restart the application (or in some setups, reload config without restart)
- No code changes, no rebuild needed
13. End-to-End Request Flow Walkthrough
Scenario
A client sends: GET /payment/12345
The application should fetch payment details for ID 12345 and return a response with paymentId, amount, and currency.
Full Flow
Code All Layers Together
Controller
1@RestController2@RequestMapping("/payment")3public class PaymentController {4
5 @Autowired6 private PaymentService paymentService;7
8 @GetMapping("/{id}")9 public PaymentResponse getPaymentDetails(@PathVariable String id) {10 // Map incoming request to internal DTO11 PaymentRequest paymentRequest = new PaymentRequest();12 paymentRequest.setPaymentId(id);13
14 // Delegate to Service15 return paymentService.getPaymentDetails(paymentRequest);16 }17}Service
1@Service2public class PaymentService {3
4 @Autowired5 private PaymentRepository paymentRepository;6
7 public PaymentResponse getPaymentDetails(PaymentRequest paymentRequest) {8 // Call Repository9 PaymentEntity entity = paymentRepository.getPaymentById(paymentRequest);10
11 // Map Entity → Response DTO12 PaymentResponse response = new PaymentResponse();13 response.setPaymentId(entity.getPaymentId());14 response.setAmount(entity.getPaymentAmount()); // field name differs from DB column15 response.setCurrency(entity.getPaymentCurrency());16
17 return response;18 }19}Repository
1@Repository2public class PaymentRepository {3
4 public PaymentEntity getPaymentById(PaymentRequest paymentRequest) {5 // In real projects: JPA / JDBC query here6 PaymentEntity entity = new PaymentEntity();7 entity.setPaymentId(paymentRequest.getPaymentId());8 entity.setPaymentAmount(1000.00);9 entity.setPaymentCurrency("INR");10 return entity;11 }12}Request DTO
1public class PaymentRequest {2 private String paymentId;3 // getter + setter4}Response DTO
1public class PaymentResponse {2 private String paymentId;3 private Double amount;4 private String currency;5 // getters + setters6}Entity
1@Entity2public class PaymentEntity {3 private String paymentId;4 private Double paymentAmount;5 private String paymentCurrency;6 // getters + setters7}HTTP Response (on port 8080)
1{2 "paymentId": "12345",3 "amount": 1000.0,4 "currency": "INR"5}Notice:
- The client sees
amount— notpaymentAmount(the internal/DB field name) - The DB column name (
payment_amount) is completely hidden from the response - This isolation is enforced by the DTO + mapping in the Service layer
14. Maven `pom.xml` Dependency Management
Overview
pom.xml (Project Object Model) is Maven's configuration file. It declares the project's dependencies, build plugins, and metadata.
Initial `pom.xml` After Spring Initializr
1<?xml version="1.0" encoding="UTF-8"?>2<project xmlns="http://maven.apache.org/POM/4.0.0"3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.05 https://maven.apache.org/xsd/maven-4.0.0.xsd">6 <modelVersion>4.0.0</modelVersion>7
8 <!-- Spring Boot parent manages dependency versions -->9 <parent>10 <groupId>org.springframework.boot</groupId>11 <artifactId>spring-boot-starter-parent</artifactId>12 <version>3.2.3</version>13 </parent>14
15 <!-- Your project identity -->16 <groupId>com.conceptandcoding</groupId>17 <artifactId>learning-spring-boot</artifactId>18 <version>0.0.1-SNAPSHOT</version>19 <name>learning-spring-boot</name>20 <description>Demo project for Spring Boot</description>21
22 <properties>23 <java.version>17</java.version>24 </properties>25
26 <dependencies>27 <!-- Spring Web: REST APIs + embedded Tomcat -->28 <dependency>29 <groupId>org.springframework.boot</groupId>30 <artifactId>spring-boot-starter-web</artifactId>31 </dependency>32
33 <!-- Testing dependency (JUnit, Mockito) -->34 <dependency>35 <groupId>org.springframework.boot</groupId>36 <artifactId>spring-boot-starter-test</artifactId>37 <scope>test</scope>38 </dependency>39 </dependencies>40
41 <build>42 <plugins>43 <plugin>44 <groupId>org.springframework.boot</groupId>45 <artifactId>spring-boot-maven-plugin</artifactId>46 </plugin>47 </plugins>48 </build>49</project>Adding More Dependencies Later
As the project grows, add dependencies directly in pom.xml. For example, to add database access:
1<!-- Spring Data JPA (database ORM) -->2<dependency>3 <groupId>org.springframework.boot</groupId>4 <artifactId>spring-boot-starter-data-jpa</artifactId>5</dependency>6
7<!-- MySQL Driver -->8<dependency>9 <groupId>com.mysql</groupId>10 <artifactId>mysql-connector-j</artifactId>11 <scope>runtime</scope>12</dependency>Maven will automatically download these from the central repository.
15. Quick Reference Table
Layers
| Layer | Package | Key Annotation | Primary Responsibility |
|---|---|---|---|
| Controller | controller/ | @RestController | Receive requests, map DTOs, delegate to Service |
| Service | service/ | @Service | All business logic |
| Repository | repository/ | @Repository | All DB operations |
Supporting Packages
| Package | Contents | Purpose |
|---|---|---|
dto/ | Request/Response DTOs | Decouple internal model from external schema |
entity/ | @Entity POJOs | Direct DB table representations |
utility/ | Static helper methods | Shared logic across multiple service classes |
config/ | Configuration classes | Externalise hardcoded values |
Annotations Summary
| Annotation | Layer / Package | What it does |
|---|---|---|
@SpringBootApplication | Main class | Entry point; enables auto-configuration, component scan |
@RestController | Controller | REST controller; returns JSON by default |
@GetMapping / @PostMapping | Controller | Maps HTTP methods to handler methods |
@Service | Service | Marks Spring service bean |
@Repository | Repository | Marks Spring data access bean |
@Entity | Entity | Marks JPA entity (DB table representation) |
@Autowired | All layers | Injects Spring beans |
@Value | Config / Service | Reads a value from application.properties |
16. Interview Notes
Q1: What is the difference between JAR and WAR? When do you use each?
Answer: JAR (Java Archive) is a standalone application with an embedded server. WAR (Web Archive) is a package for deployment to an external server and typically includes web resources like HTML/CSS/JS. In modern microservices, JAR is standard — each service is self-contained. WAR is used in legacy deployments or when working with traditional servlet containers.
Q2: What is layered architecture? Why is it important?
Answer: Layered architecture divides a Spring Boot application into distinct layers — Controller (API entry point), Service (business logic), and Repository (data access). Each layer has a single clear responsibility. Benefits: separation of concerns, independent testability, easier maintenance, changes in one layer don't cascade to others, and the structure is recognisable to any Spring Boot developer.
Q3: What should the Controller layer NOT contain?
Answer: Business logic. The Controller should only receive requests, map external data to DTOs, delegate to the Service layer, and return responses. Any calculation, decision, or transformation is the Service layer's responsibility.
Q4: What is a DTO and why do we use it?
Answer: A Data Transfer Object is a plain Java class used to carry data between layers or between the application and external clients. Request DTOs decouple the internal field names from what clients send — if the external schema changes, only the controller mapping changes. Response DTOs control exactly which fields are exposed, preventing internal DB column names from leaking to clients.
Q5: What is the difference between an Entity and a DTO?
Answer: An Entity is a Java class that directly maps to a database table (annotated with @Entity). Its fields match DB column names. A DTO is a plain Java class used to transfer data to/from clients or between layers. Entities are used by the Repository layer; DTOs are used by the Controller and Service layers. You should never return an Entity directly to a client — always map to a Response DTO first.
Q6: Which layer should interact with the database?
Answer: Only the Repository layer. The Service layer calls the Repository layer to get or persist data. The Controller layer should never directly access the database. This separation ensures DB logic is isolated, making it easy to swap database technologies or mock the repository in tests.
Q7: Why should values be externalised to `application.properties` instead of hardcoding?
Answer: Hardcoded values require a code change + rebuild + redeployment whenever the value needs to change. Externalised config (in application.properties) can be changed without any code changes. In production, this allows configuration changes to be applied to a running system quickly and safely.
Q8: What does `@SpringBootApplication` do?
Answer: It is a convenience annotation that combines three annotations: @Configuration (marks the class as a source of bean definitions), @EnableAutoConfiguration (enables Spring Boot's auto-configuration), and @ComponentScan (tells Spring to scan the current package and sub-packages for Spring components like @Controller, @Service, @Repository).
Q9: What is Spring Initializr?
Answer: Spring Initializr (start.spring.io) is an online tool that generates a Spring Boot project skeleton. You select your build tool (Maven/Gradle), language, Spring Boot version, Java version, dependencies, and project metadata. It generates and downloads a .zip file containing a ready-to-import project with a configured pom.xml and a main application class.
Q10: What is the embedded server in Spring Boot and what does it mean?
Answer: Spring Boot includes an embedded Tomcat server (by default) inside the JAR file. This means the application is completely self-contained — you don't need to install or configure an external Tomcat or any other server. You run the application with java -jar app.jar and it starts its own server on the configured port (default: 8080).
17. Common Mistakes
1// ❌ Wrong2@GetMapping("/{id}")3public PaymentResponse getPayment(@PathVariable String id) {4 // Business logic in controller — violates layered architecture5 double tax = fetchAmount(id) * 0.18;6 return buildResponse(tax);7}8
9// ✅ Correct — delegate to Service10@GetMapping("/{id}")11public PaymentResponse getPayment(@PathVariable String id) {12 PaymentRequest request = new PaymentRequest();13 request.setPaymentId(id);14 return paymentService.getPaymentDetails(request);15}1// ❌ Wrong — Service directly calls DB2@Service3public class PaymentService {4 @Autowired5 private JdbcTemplate jdbcTemplate;6
7 public Payment getPayment(String id) {8 // Direct DB access in service — should go through Repository9 return jdbcTemplate.queryForObject("SELECT ...", ...);10 }11}12
13// ✅ Correct — Service calls Repository, Repository accesses DB1// ❌ Wrong — exposes DB column names and internal structure2@GetMapping("/{id}")3public PaymentEntity getPayment(@PathVariable String id) {4 return paymentRepository.findById(id); // leaks internal DB field names5}6
7// ✅ Correct — map Entity to Response DTO in Service layer, return DTO8@GetMapping("/{id}")9public PaymentResponse getPayment(@PathVariable String id) {10 return paymentService.getPaymentDetails(id);11}1// ❌ Wrong — hardcoded values require code change to modify2int timeout = 5000;3String apiUrl = "https://api.example.com/v1";4
5// ✅ Correct — read from application.properties via @Value6@Value("${payment.timeout}")7private int timeout;8
9@Value("${payment.apiUrl}")10private String apiUrl;1// ❌ Wrong for microservices2<packaging>war</packaging>3
4// ✅ Correct for microservices5<packaging>jar</packaging>18. Best Practices
- Always follow layered architecture — Controller → Service → Repository — even for small applications. The habits built here scale to large projects.
- Never put business logic in Controller or Repository. If you find yourself writing
if/elseor calculations in a controller, move it to Service.
- Always use DTOs — never pass Entity objects to controllers or return them in HTTP responses.
- Externalise all configuration to
application.properties. No hardcoded URLs, timeouts, credentials, or thresholds in source code.
- Keep each class focused — one controller per feature area (
PaymentController,UserController), one service per feature (PaymentService,UserService).
- Name packages clearly —
controller,service,repository,dto,entity,utility,config. Standard naming makes onboarding instant.
- Add dependencies incrementally — start with only what you need (e.g.,
spring-boot-starter-web). Add more topom.xmlas features require them.
- Use
spring-boot-starter-testfor unit testing each layer independently using JUnit and Mockito.
- Never commit credentials in
application.properties. Use environment variables or a secrets manager for sensitive values (passwords, API keys).
- Use Spring Data JPA for the Repository layer rather than writing raw JDBC code — it provides ready-made CRUD methods and eliminates boilerplate SQL.
19. Practice Questions
Easy
- What is the URL for Spring Initializr?
- What is the difference between Group and Artifact in project metadata?
- Which packaging should you choose for a microservice and why?
- Name the three core layers in Spring Boot layered architecture and their annotations.
- What is the default port that Spring Boot's embedded Tomcat starts on?
Medium
- Explain the flow of a
POST /paymentrequest through all three layers, from the client sending data to the client receiving a response. - Why do we use Request DTOs instead of directly passing client request parameters to the Service layer?
- What is the difference between an Entity and a Response DTO? Why should you never return an Entity from a controller?
- A developer hardcoded
int maxRetry = 3in a Service class. Explain the problem and show how to fix it usingapplication.propertiesand@Value. - If the client changes the request field name from
idtoreferenceNumber, which layer needs to change and why?
Hard
- Design the complete layered architecture for a
UserServicethat exposes:
POST /user— create a userGET /user/{id}— fetch a userDELETE /user/{id}— delete a user
Show all classes across all layers with their fields and key methods.
- Explain what happens at the JVM and framework level when a Spring Boot JAR starts: from
java -jar app.jarto "Tomcat started on port 8080".
- A senior developer tells you: "The Service layer should never know about HTTP." What do they mean, and how does the layered architecture enforce this?
- In a production system, you have 10 microservices all reading from the same
application.propertiesconfig. A timeout value needs to change. What problem does this present, and how does Spring Cloud Config Server solve it?
- Why is it a security risk to return an
@Entityobject directly in a REST API response? Give two concrete examples of what could go wrong.
20. Summary
Quick Revision Bullets
- Spring Initializr (
start.spring.io) generates a project skeleton withpom.xmland a main@SpringBootApplicationclass - JAR = standalone app with embedded Tomcat — correct choice for microservices; WAR = external server deployment — legacy use case
- Controller layer (
@RestController): receives HTTP requests, maps to Request DTO, delegates to Service, returns Response DTO - Service layer (
@Service): all business logic lives here — never in Controller or Repository - Repository layer (
@Repository): only layer that accesses the database; returns Entity objects - Request DTO: maps external client fields to internal field names; isolates controller from internal changes
- Response DTO: controls which fields are sent to the client; prevents DB column names from leaking
- Entity (
@Entity): POJO that directly mirrors a DB table; used by Repository; never returned directly to clients - Utility package: shared helper methods used across multiple service classes
- Configuration: externalise all values to
application.propertiesand read with@Value— no hardcoded constants in code - Default port: embedded Tomcat starts on
8080; configurable viaserver.portinapplication.properties - Dependencies are added in
pom.xml; Spring Boot parent manages version compatibility automatically
This guide covers Spring Boot project setup and layered architecture as commonly implemented in enterprise Java microservices. For further depth, explore Spring Data JPA (Repository layer), Spring Security, and Spring Cloud Config.
Mastery check
How well can you recall this?
Finished this lesson?