





Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Best practices for developing spring boot applications, covering topics such as package naming, class naming, method naming, variable naming, enum naming, configuration naming, code readability, exception handling, logging, dtos vs entities, immutability, testing, build & dependency management, and api documentation. It provides practical examples and recommendations to improve code quality, maintainability, and security in spring boot projects. The guide is intended for developers looking to enhance their spring boot development skills and follow industry standards.
Typology: Study Guides, Projects, Research
1 / 9
This page cannot be seen from the preview
Don't miss anything!






This document outlines standardized Java coding conventions and best practices to be followed in real-time, production-grade projects. It serves as a guideline for developers to write clean, maintainable, scalable, and secure code. It covers naming conventions, project structure, code formatting, exception handling, design principles. Adhering to these standards will ensure code consistency across the team, reduce technical debt, and improve collaboration in real-world enterprise applications.
🔹 1. Project Structure (Modular, Layered Architecture) Structure your project by layers: 📁 projectname ├── 📁 src │ ├── 📁 main │ │ ├── 📁 java │ │ │ └── 📁 com.companyname.projectname │ │ │ ├── 📁 controller → REST controllers │ │ │ ├── 📁 service → Business logic │ │ │ ├── 📁 repository → JPA repositories │ │ │ ├── 📁 model → Entities (JPA) │ │ │ ├── 📁 dto → Data Transfer Objects │ │ │ ├── 📁 mapper → MapStruct or custom mappers │ │ │ ├── 📁 config → Spring configs (e.g., SecurityConfig) │ │ │ ├── 📁 exception → Custom exceptions & handlers │ │ │ ├── 📁 util → Utility/helper classes │ │ │ └── 📁 security → Authentication & authorization │ │ └── 📁 resources │ │ ├── 📄 application.yml → Main config file │ │ ├── 📁 static → Static assets (JS, CSS, etc.) │ │ ├── 📁 templates → Thymeleaf/FreeMarker templates │ │ ├── 📁 i18n → Localization files │ │ └── 📁 log → Log file storage (if configured │ │ to write here) │ └── 📁 test │ └── 📁 java │ └── 📁 com.companyname.projectname │ ├── 📁 controller │ ├── 📁 service │ └── ... (tests matching main structure) ├── 📁 target → Compiled classes and build artifacts │ (generated) ├── 📄 pom.xml → Maven build configuration ├── 📄 .gitignore → Git ignored files list └── 📄 README.md → Project overview & instructions
🔹 2. Package Naming ● Standard: All lowercase , dot-separated, hierarchical. ● Pattern: com.company.project.module ✦ Example: com.example.crm.user.service com.example.crm.auth.controller Com.example.crm.common.exception
🔹 3. Class Naming ● Standard: PascalCase (UpperCamelCase) ● Suffixed types: → Controller : UserController → Service : UserService, AuthServiceImpl → DTOs : UserRequestDto, UserResponseDto → Entities : User, Role → Repositories : UserRepository ✦ Example: public class UserServiceImpl implements UserService
🔹 4. Method Naming Standard: camelCase (verbs first, descriptive) Common patterns: → getAllUsers() → findUserById() → saveUser() → deleteUserById() → assignRolesToUser()
🔹 5. Variable Naming ● Standard: camelCase , meaningful names (no abbreviations) ✦ Examples: → String userName ; → Long userId ; → List
🔹 6. Constant Naming (e.g., Roles like ROLE_AGENT) Standard: UPPER_SNAKE_CASE , usually in enums or constants classes. Defined in Enum: Best practice in Spring Security ✦ Example : public enum ERole { ROLE_USER , ROLE_AGENT , ROLE_ADMIN ,
✦ Example : ● Creating custom exception RoleNotFoundException
import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation. ResponseStatus ;
@ResponseStatus (HttpStatus. NOT_FOUND ) public class RoleNotFoundException extends RuntimeException { public RoleNotFoundException (String message) { super (message); } } }
● If an Exception occurs, we should handle it Globally. @Slf4j // logging purpose @RestControllerAdvice @AllArgsConstructor public class GlobalExceptionController {
@ExceptionHandler (RoleNotFoundException. class ) public ResponseEntity
🔹 11. Logging (Structured, Not System.out) ● Use SLF4J (@Slf4j) instead of System.out. ● Log only meaningful data ( not passwords, sensitive info ). ● Use placeholders instead of string concatenation:
✦ Example : log .info( "User created: id={}, name={}" , user.getId(), user.getName());
🔹 12. Validation (Always Validate Input) ● Use javax.validation (@NotNull, @Size, etc.) on DTOs ✦ Example: public class UserRequestDto { @NotBlank private String username ; @Email private String email ; }
● Use @Valid in controller methods: ✦ Example public ResponseEntity<?> createUser ( @Valid @RequestBody UserRequestDto request) { ... }
🔹 13. Security (Spring Security Best Practices)
🔹 14. DTOs vs Entities (Separation of Concerns)
Real-world example :
@Entity @Table (name = "users" ) public class User {
@Id @GeneratedValue (strategy = GenerationType.IDENTITY) private Long id ;
private String username ; private String email ;
@Enumerated (EnumType.STRING) private Status status ; // Getters and setters (or use Lombok) }
✦ UserRequestDto.java – for incoming requests
public class UserRequestDto {
@NotBlank private String username ;
@RestController @RequestMapping("/api/users") @RequiredArgsConstructor public class UserController {
private final UserService userService;
@PostMapping public ResponseEntity
@GetMapping public ResponseEntity<List
🔹 15. Immutability & Lombok Usage ● Use @Value or final for immutable objects. ● Use Lombok sparingly and only in DTOs or model layers: ● @Data, @Builder, @Getter, @Setter, @NoArgsConstructor, @AllArgsConstructor
✦ Example: DTO Using Lombok & Immutability UserResponseDto.java import lombok.Builder; import lombok.Value;
@Value @Builder public class UserResponseDto { Long id ; String username ; String email ; String status ; }
➤ Note : @Value makes the class:
✦ Example: Entity (Mutable, Use Lombok Carefully) User.java @Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class User {
@Id @GeneratedValue (strategy = GenerationType. IDENTITY ) private Long id ;
private String username ; private String email ;
@Enumerated (EnumType.STRING) private Status status ; }
➤ Note :⚠ Avoid @Data on JPA entities because: ● It adds toString(), which can cause circular reference issues in bi-directional relationships. ● Adds equals() and hashCode(), which can break persistence behavior (especially with proxies).
✦ Example: Request DTO with @Builder (Mutable or Immutable) UserRequestDto.java import lombok.Builder; import lombok.Data;
@Data @Builder public class UserRequestDto { private String username ; private String email ; }
➤ Note : Use @Data + @Builder for flexible and clean object creation in mutable DTOs.
✦ Example : Anti-pattern: @Data on Entity