A sample Spring Boot Api with Spring JPA and Spring Security JWT token and folder structure "best practices" known at this moment. This project is being improved.
This project suggests a structure that follows some good practices principles, some of them inspired on Clean Code
and Angular Framework
. The Base package implementation starts on src/main/java/com/github/yangricardo/api_spring_boot.
src/main/java/com/github/yangricardo/api_spring_boot
├── ApiSpringBootApplication.java
├── modules
└── shared
The Main Class that should start the execution is ApiSpringBootApplication.java. After that, there is two folders structures: modules
and shared
.
The modules
contains specific application implementations. For each module, you could follow the structure found at ./modules/module_structure_reference folder:
src/main/java/com/github/yangricardo/api_spring_boot/modules/module_structure_reference
├── controllers
├── model
├── repository
└── services
It's not necessary to implement all the suggested modules. You can delete the folders that does not make sense to the module to be implemented
In each folder we should arrange:
model
: AllJPA Entities
andDTOs (Data Transfer Objects)
classes related to the module.repository
: AllJPA Entities
andDTOs (Data Transfer Objects)
classes related to the module.services
: All classes that implement business logic, like how the data can be saved on the eachRepository
and other support modulescontrollers
: All REST Controllers that exposes HTTP API endpoints for services.
This project disposes an CRUD api for a
/value
resource, that stores only a string value:
src/main/java/com/github/yangricardo/api_spring_boot/modules/value
├── controllers
│ └── ValueController.java
├── model
│ └── Value.java
├── repository
│ └── IValueRepository.java
└── services
├── IValueService.java
└── ValueServiceImpl.java
The Shared folder structure contains all generic codes that is someway shared by the specific modules:
src/main/java/com/github/yangricardo/api_spring_boot/shared/
├── configurations
└── modules
The shared modules
contains:
src/main/java/com/github/yangricardo/api_spring_boot/shared/modules
├── controllers
│ └── BaseController.java
└── models
└── BaseModel.java
-
The BaseModel contains an abstract class that implements some common properties like:
id
: a Long typed column that holds the integer primary key from each record.uuid
: a UUID typed column that holds the UUID unique key from each record. This also has an associatedhibernate annotation
method that generate this valueon pre persist event
.createdAt
: a date typed column that holds the Date of creation of the record. This also has an associatedhibernate annotation
method that generate this valueon pre persist event
.updatedAt
: a date typed column that holds the Date of the last update on the record. This also has an associatedhibernate annotation
method that generate this valueon pre updated event
.
-
The BaseController contains common methods and configurations shared by the specific
RESTControllers
The authentication of this api is main configured on SecurityConfiguration and with Auth
module implementations:
src/main/java/com/github/yangricardo/api_spring_boot/modules/auth
├── controllers
│ └── AuthenticationController.java
├── model
│ ├── CreateUserDTO.java
│ ├── LoginDTO.java
│ └── TokenDTO.java
├── repository
└── services
├── AuthenticationService.java
├── TokenAuthenticationFilterService.java
└── TokenIssuerService.java
The Auth
module manages how the users are created and authenticated on the API by the services implementations:
-
The AuthenticationService provides implementations to find the
UserDetails
Spring Security interface by theUserDetailsService::loadUserByUsername
. Also disposes acreateUser
method to securely create a user and process the hash Password before save an new user record. -
The TokenIssuerService disposes methods for
JWT (JSON Web Tokens)
issue, validation and user metadata identification. -
The TokenAuthenticationFilterService implements the
OncePerRequestFilter
that implements the logic for the JWT Authentication Middleware validation. -
The SecurityConfiguration implements the
WebSecurityConfigurerAdapter
to configure theAuthenticationManager
object andHTTP requests
authorization for route patterns.
Note that the AuthenticationService uses an
Users module
:
src/main/java/com/github/yangricardo/api_spring_boot/modules/users
├── controllers
├── model
│ ├── AuthorizationProfile.java
│ └── User.java
├── repository
│ └── IUserRepository.java
└── services
├── IUserService.java
└── UserService.java
This is an base implementation for users resources. Note that the User model implements an
UserDetails
Spring Security interface and has could have many AuthorizationProfile records, that implements theGrantedAuthority
Spring Security interface in order to implement RBAC functionalities for roles and privileges management.
Avoid basic implementations with Lombok annotations
Recommended usage as it provide annotations that avoid the write of bloated code, as it turns easier to write class without the need to implement constructors, builders, getters and setters methods
Validate classes contend with Javax Validation and Hiberna annotations
Recommended to usage on Classes content validation.
Disposes SWAGGER based documentation with SpringFox
Recommended to dispose the REST API endpoints available and document it's usage
Serializing operations of Java classes to JSON objects notation with Jackson object mappers
See the implementation of the Bean object mapper at ObjectMapperConfiguration to use @Autowired
object or create variations for the bean context application object
Enhance development experience
Making HTTP calls for externals services with WebClient from Spring WebFlux
The WebClient is part of Spring WebFlux library and perform modern ways to handle both client and server operations. The WebClient provides easy way to handle HTTP requests based on Spring WebFlux concepts of Reactive requests
Becoming an Reactive Rest API with Spring WebFlux
TODO
- Java 11
This project uses Postgres
as main database for JPA integration. If you use another, update the configuration for integrate with another database like MySQL
or SQL Server
.
This project provides a docker-compose.yaml with default database
This project provides a Dockerfile and docker-compose.yaml with default configurations for the dockerization of this api. Also is provided a shell build script that performs Maven
and Docker Image
build executions.
-
Install the ASDF
Make sure to follow your shell environment instructions, like
bash
orzsh
-
Enable the ASDF plugin for Java:
asdf plugin add java
Make sure to follow your shell environment instructions, like
bash
orzsh
, by setting the JAVA_HOME -
Find a Java version:
asdf list all java
-
Install a Java version:
asdf install java corretto-11.0.13.8.1
This project is developed using the AWS Java Correto 11 distribution
-
Enable the Java's ASDF installed version globally:
asdf global java corretto-11.0.13.8.1
-
Install the Visual Studio Code
-
Install the Java Extension Pack
-
Install the Spring Boot Tools
-
Make sure that the environment recognizes your Java Runtime.
Sometimes, the ASDF Java installation is not recognized by Visual Studio code. In that case, update the settings.json by going on the
Preferences > Settings
add add or update with the following sample, changing with your path for the JAVA_HOME and Java Runtimes:{ "java.configuration.runtimes": [ { "name": "JavaSE-11", "path": "/home/kali/.asdf/installs/java/corretto-11.0.13.8.1", "default": true } ], "java.home": "/home/kali/.asdf/installs/java/corretto-11.0.13.8.1" }
-
Install Lombok plugin to improve Lombok annotations usage on code implementation