8/21/2021

Layered Architecture of Spring Boot Application

 



The purpose of this blogpost is to explain main components and layers of a simple spring boot application and how to develop them.

Please find the source code for above application.


Rest Controller

https://github.com/dhanuka84/sb-transaction-service/blob/main/src/main/java/com/sb/transaction/service/web/controllers/TransactionController.java



  • This is sample post method.
  • Request body can be validated with @Validate annotation.
  • HTTP status code for success scenario can be mentioned with @ResponseStatus annotation.
  • URI is /sb/transactions.
  • We can use ResponseStatusException for other HTTP status code based on each scenario.

Service Implementation




  • Logging can be initialized by lombok @Slf4j annotation .
  • Constructor with argument can be created with lombok @RequiredArgsConstructor annotation .
  • We can map DTO to domain object and wise versa using transactionMapper .
  • Using transactionRepository we can persist the domain object in database through JPA/JDBC .


JPA Repository/Backend Layer

https://github.com/dhanuka84/sb-transaction-service/blob/main/src/main/java/com/sb/transaction/service/repositories/TransactionRepository.java



  • Most of the commonly used CRUD operations based on domain entity and primary key can be found from JpaRepository .
  • For the native query, we have used a custom method. 




  • Native query can be found in the same domain entity class Transaction .
  • The name of the native query should be : (Entity class name) . ( Domain Repository method name) - @NamedNativeQuery(name = "Transaction.findStatistics",
  • @SqlResultSetMapping(name = "Mapping.StatisticsDto" : This will map sql result set to DTO.
  • Please note that constructor of DTO have to create manually since order of argument data type should match with @SqlResultSetMapping columns.
public StatisticsDto(BigDecimal sum, BigDecimal avg, BigDecimal max, BigDecimal min,Long count) 


Spring Boot Application : Where Every things Begins







Data Mapper





  • We can use multiple mapper classes like DateMapper.class .
  •  componentModel = "spring" should be mentioned, then only mapstruct can be used within spring.
  • DateMapper useful when we deserialize JSON to java object and wise versa since parser can identify Java 8 Date Time package.

Mockito with Spring Boot


 

  • Don't forget to import correct @Test annotation.

                import org.junit.jupiter.api.Test;


Spring Configuration

https://github.com/dhanuka84/sb-transaction-service/blob/main/src/main/resources/application.properties

  • Server port and name can be configured here


Application and Docker image building








No comments:

Post a Comment