π§© 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 π








Top comments (0)