Şuayb's BlogŞuayb's Blog
Home
Categories
Games
MediumAboutContact
Language
Theme
    1. Blog
    2. Programming
    3. Clean Coding Practices in Spring Boot

Clean Coding Practices in Spring Boot

PublishedDecember 19, 2024
UpdatedDecember 20, 2024
Reading time3 min read
JavaKotlinSpring BootClean Coding
XLinkedInFacebook
Clean Coding Practices in Spring Boot

Loading likes...

Clean coding practices ensure that your Spring Boot applications are maintainable, readable, and scalable. This guide provides essential tips and code examples to help you write cleaner and more efficient code in both Java and Kotlin.


Last updatedDecember 20, 2024

Total viewsLoading hits...

Previous articleSpring Boot DevToolsNext articleSpring Boot with OpenAPI
Şuayb Şimşek

Written by

Şuayb Şimşek

Backend-focused fullstack developer sharing practical notes on Spring Boot, security, microservices, and cloud-native architecture.

Expertise

  • Spring Boot
  • Go
  • Microservices
  • Next.js
  • Cloud Native

Connect

GitHubLinkedInMedium

Related posts

Spring Boot Configuration Properties
Programming

Spring Boot Configuration Properties

Learn how to use @ConfigurationProperties for type-safe configuration, validate settings with @Validated, and manage environment-specific values with profile-specific application-{profile}.yml files.

February 4, 20263 min read
JavaKotlinSpring BootConfiguration
Spring Boot GraphQL JWE Authentication
Programming

Spring Boot GraphQL JWE Authentication

Learn how to secure your Spring Boot GraphQL APIs with stateless encrypted JWTs (JWE) while persisting user identities and roles in a JPA-backed database.

May 17, 20256 min read
JavaKotlinSpring BootSecurityJWTJWEGraphQL
Spring Boot JWE Authentication with JPA
Programming

Spring Boot JWE Authentication with JPA

Learn how to use stateless encrypted JWTs (JWE) to secure your Spring Boot APIs while persisting user identities and roles in a JPA-backed database.

May 11, 20254 min read
JavaKotlinSpring BootSecurityJWTJWEJPA

About

Articles on Spring Boot, microservices, security, and more.

ContactStart here

Latest posts

  • Captain Tsubasa 2: World Fighters
  • Captain Tsubasa: Rise of New Champions
  • Spring Boot Configuration Properties
  • Spring Boot GraphQL JWE Authentication
  • Spring Boot JWE Authentication with JPA

Top topics

JavaKotlinSpring BootJWEJWTMicroservice

Subscribe

Get practical backend + fullstack notes when new articles are published.

Social

© 2024-2026 Şuayb's Blog. All rights reserved.

🌟 Why Focus on Clean Coding?

Adopting clean coding principles helps to:

  • Improve code readability and maintainability.
  • Reduce technical debt.
  • Make onboarding new developers easier.
  • Enhance scalability and debugging processes.

📋 Prerequisites

📋 Ensure you have the following:

  • ☕ Java Development Kit (JDK) 17+
  • 📦 Maven or Gradle installed
  • 🔤 A Java IDE (e.g., IntelliJ IDEA, Eclipse)
  • 🛠️ Familiarity with Spring Boot basics

🛠️ Step 1: Structure Your Project

Organize your Spring Boot project for better clarity:

  • Controller Layer: Handles incoming HTTP requests.
  • Service Layer: Contains business logic.
  • Repository Layer: Interacts with the database.

Example Folder Structure:

This structure keeps layers separated and makes future refactoring safer as the project grows.

FILENAME
src/main/java/com/example/cleanproject
├── controller
├── service
├── repository
├── entity
└── dto

🛠️ Step 2: Use Lombok for Cleaner Java Code

Lombok reduces boilerplate code in Java, making your classes more concise and readable. Here's how to use Lombok effectively:

Add Lombok Dependency

Start by adding Lombok to your build so annotations are resolved correctly before refactoring your entities and DTOs.

  • Maven:
XMLpom.xml
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <scope>provided</scope>
</dependency>
  • Gradle:
GROOVYbuild.gradle
provided 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'

Example: Entity with Lombok

The following example gives practical context for Example: Entity with Lombok and can be applied directly.

JAVAUser.java
package com.example.cleanproject.entity;

import jakarta.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String email;
}

Benefits:

  • @Data generates getters, setters, equals, hashCode, and toString methods.
  • @NoArgsConstructor and @AllArgsConstructor create constructors.

🛠️ Step 3: Write Concise and Readable Code in Kotlin

Kotlin offers modern features that naturally lead to cleaner code:

Example: Entity in Kotlin

The following example gives practical context for Example: Entity in Kotlin and can be applied directly.

KOTLINUser.kt
package com.example.cleanproject.entity

import jakarta.persistence.*

@Entity
data class User(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long = 0,
    var name: String,
    var email: String
)

Advantages of Kotlin:

  • data class automatically generates toString, equals, and hashCode methods.
  • Immutable properties (val) ensure better stability.

🛠️ Step 4: Follow Dependency Injection Principles

Use dependency injection to decouple components and improve testability.

Example: Service Layer with DI

The following example gives practical context for Example: Service Layer with DI and can be applied directly.


🛠️ Step 5: Use DTOs for Data Transfer

Data Transfer Objects (DTOs) separate your domain and API layers, promoting better encapsulation.

Example: DTO for User

The following example gives practical context for Example: DTO for User and can be applied directly.


Controller Layer

Implement a controller to handle HTTP requests and interact with the service layer.


▶️ Running the Application

Run the application using the following command:

BASH
./mvnw spring-boot:run

Test endpoints using a tool like Postman or cURL.


🧪 Testing the API

You can test the API using the following cURL command:

  • Fetch all users:
BASH
curl -X GET http://localhost:8080/api/users

🏁 Conclusion

You now have a practical Clean Coding Practices in Spring Boot implementation with a clear, production-friendly Spring Boot structure. As a next step, adapt configuration and tests to your own domain, then validate behavior under realistic traffic and failure scenarios.

JAVAUserService.java
package com.example.cleanproject.service;

import com.example.cleanproject.entity.User;
import com.example.cleanproject.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
}
KOTLINUserService.kt
package com.example.cleanproject.service

import com.example.cleanproject.entity.User
import com.example.cleanproject.repository.UserRepository
import org.springframework.stereotype.Service

@Service
class UserService(
    private val userRepository: UserRepository
) {
    fun getAllUsers(): List<User> = userRepository.findAll()
}
JAVAUserDTO.java
package com.example.cleanproject.dto;

import lombok.Data;

@Data
public class UserDTO {
    private String name;
    private String email;
}
KOTLINUserDTO.kt
package com.example.cleanproject.dto

data class UserDTO(
    val name: String,
    val email: String
)
JAVAUserController.java
package com.example.cleanproject.controller;

import com.example.cleanproject.dto.UserDTO;
import com.example.cleanproject.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @GetMapping
    public List<UserDTO> getAllUsers() {
        return userService.getAllUsers();
    }
}
KOTLINUserController.kt
package com.example.cleanproject.controller

import com.example.cleanproject.dto.UserDTO
import com.example.cleanproject.service.UserService
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/api/users")
class UserController(
    private val userService: UserService
) {

    @GetMapping
    fun getAllUsers(): List<UserDTO> = userService.getAllUsers()
}