🧩 Understanding a Real-World Spring Boot Project Structure (Best Practices)
When you start working with Spring Boot, everything feels simple… until your project grows.
Then suddenly:
😵Too many files
😵💫Confusing structure
❌Hard to maintain code
In this article, I’ll walk you through a clean and scalable Spring Boot project structure based on a real example.
📁 Project Overview
Here’s a simplified view of the structure:
src/main/java/org.sid
├── controllers
├── dto
├── entities
├── enums
├── mappers
├── repositories
├── securityKeycloak
├── services
Each layer has a clear responsibility, which makes the application maintainable and scalable.
🎯 1. Entities (entities)
Represents database tables.
🧠 2. Repository Layer (repositories)
This layer communicates with the database.
👉 Uses Spring Data JPA
✅ No implementation needed — Spring generates it automatically!
🗄️ 3. DTOs (dto)
DTO = Data Transfer Object
👉 Used to send data between layers safely

✅ Why use DTOs?
_Protect sensitive Data:_
In a Spring Boot application, a DTO (Data Transfer Object) is used to transfer data between layers, especially between the backend and the client.
It is used to protect sensitive data: entities often contain sensitive fields such as passwords. If you return these entities directly, it can create a security risk.
Control API response:
A DTO (Data Transfer Object) allows you to decide exactly what data is sent to the client instead of exposing your full Entity.
🔁 4. Mappers (mappers)
Convert between Entity ↔ DTO
public class AccountMapper {
public static AccountDTO toDTO(Account account) {
// mapping logic
}
}
💡 You can also use MapStruct for cleaner code.
🔄 5. Service Layer (services)
This is where business logic lives.
👉 Acts as a bridge between controller and repository
@Service
public class AccountService {
public List<AccountDTO> getAllAccounts() {
// business logic here
}
✅ Responsibilities:
- Business rules
- Data processing
- Validation
📦 6.Controllers Layer (controllers)
This is the entry point of your application.
👉 Handles HTTP requests (GET, POST, PUT, DELETE)
Example:
✅ Best Practice:
Keep controllers thin , No business logic here
⚠️ Important:
Do NOT expose entities directly in APIs
🔢 7. Enums (enums)
Used for fixed values like:
🔐 8. Security (securityKeycloak)
Handles authentication & authorization.
👉 In my case: Keycloak integration
Responsibilities:
- JWT validation
- User roles
- Secure endpoints
🔄 How Everything Works Together
Here’s the flow:
- Client sends HTTP request
- Controller receives it
- Service processes logic
- Repository fetches data
- Mapper converts Entity → DTO
- Response returned to client
🚀 Best Practices Recap
✅ Use layered architecture
✅ Never expose entities
✅ Keep controllers clean
✅ Use DTOs + Mappers
✅ Separate business logic in services
🎯 Conclusion
A well-structured Spring Boot project is the key to building scalable and maintainable applications.
Happy coding 🚀






