Quicly Build a Microservice using Spring Boot


1. Build Empty Spring Boot Application

Create a new Spring Boot project using Spring Initializr or your preferred IDE.

Include the following dependencies:

Generated main class:

                @SpringBootApplication
                public class MyMicroserviceApplication {
                    public static void main(String[] args) {
                        SpringApplication.run(MyMicroserviceApplication.class, args);
                    }
                }
            

2. Build Database-Related Logic (Entities, Repositories, and DTOs)

Define a database entity using the @Entity annotation, a primary key using @Id, and a repository interface.


                @Entity
                public class Account {
                    @Id
                    @GeneratedValue(strategy = GenerationType.IDENTITY)
                    private Long id;
                    private String accountNumber;
                    private Double balance;
                }
            

Create a repository interface:


                @Repository
                public interface AccountRepository extends JpaRepository<Account, Long> {
                }
            

DTO for transferring data:


                public class AccountDTO {
                    private String accountNumber;
                    private Double balance;
                }
            

3. Build Business Logic (Service Layer)

Create a service class with business logic using @Service and @Transactional.


                @Service
                public class AccountService {
                    private final AccountRepository accountRepository;
                    @Autowired
                    public AccountService(AccountRepository accountRepository) {
                        this.accountRepository = accountRepository;
                    }
                    @Transactional
                    public Account createAccount(AccountDTO accountDTO) {
                        Account account = new Account();
                        account.setAccountNumber(accountDTO.getAccountNumber());
                        account.setBalance(accountDTO.getBalance());
                        return accountRepository.save(account);
                    }
                }
            

4. Build Global Exception Handling Logic

Use @ControllerAdvice and @ExceptionHandler to handle exceptions globally.


                @ControllerAdvice
                public class GlobalExceptionHandler {
                    @ExceptionHandler(ResourceNotFoundException.class)
                    public ResponseEntity<ErrorResponse> handleNotFoundException(ResourceNotFoundException ex) {
                        ErrorResponse errorResponse = new ErrorResponse("NOT_FOUND", ex.getMessage());
                        return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
                    }
                }
            

5. Perform Data Validation on the Input

Use @Valid, @NotNull, @Size, and other validation annotations in DTOs.


                public class AccountDTO {
                    @NotNull
                    @Size(min = 10, max = 10)
                    private String accountNumber;
                    @NotNull
                    @Min(0)
                    private Double balance;
                }
            

In the controller, validate the DTO:


                @RestController
                public class AccountController {
                    private final AccountService accountService;
                    @Autowired
                    public AccountController(AccountService accountService) {
                        this.accountService = accountService;
                    }
                    @PostMapping("/accounts")
                    public ResponseEntity<Account> createAccount(@Valid @RequestBody AccountDTO accountDTO) {
                        return new ResponseEntity<>(accountService.createAccount(accountDTO), HttpStatus.CREATED);
                    }
                }
            

6. Perform Auditing Using Spring Data JPA

Enable auditing using @EnableJpaAuditing and mark the entity fields with auditing annotations like @CreatedDate and @LastModifiedDate.


                @Entity
                @EntityListeners(AuditingEntityListener.class)
                public class Account {
                    @Id
                    @GeneratedValue(strategy = GenerationType.IDENTITY)
                    private Long id;
                    @CreatedDate
                    private LocalDateTime createdDate;
                    @LastModifiedDate
                    private LocalDateTime lastModifiedDate;
                }
            

Enable auditing in the Spring Boot application class:


                @SpringBootApplication
                @EnableJpaAuditing
                public class MyMicroserviceApplication {
                    public static void main(String[] args) {
                        SpringApplication.run(MyMicroserviceApplication.class, args);
                    }
                }
            

7. Documenting REST API Using Springdoc OpenAPI

Add annotations such as @Operation, @ApiResponse, and @Schema to document your API.


                @RestController
                @Tag(name = "Account Controller", description = "REST APIs for managing accounts")
                public class AccountController {
                    @Operation(summary = "Create an account")
                    @ApiResponse(responseCode = "201", description = "Account created successfully")
                    @ApiResponse(responseCode = "400", description = "Invalid input")
                    @PostMapping("/accounts")
                    public ResponseEntity<Account> createAccount(@Valid @RequestBody AccountDTO accountDTO) {
                        return new ResponseEntity<>(accountService.createAccount(accountDTO), HttpStatus.CREATED);
                    }
                }
            

With these steps, you have built a robust, well-documented microservice in Spring Boot!