Spring - yibinericxia/documents GitHub Wiki
Spring Framework
Spring framework provides a comprehensive infrastructure for developing Java/Kotlin applications, such as Spring MVC, Spring ORM/JDBC, Spring Security, Spring AOP, Spring Test, etc.
Spring supports both the legacy web.xml and Servlet 3 (SpringServletContainerInitializer) as its bootstrap entry point.
Spring Boot
Spring Boot is an extension of the Spring framework with opinionated ‘starter' dependencies and an embedded server to eliminate the boilerplate configurations for setting up a Spring application as well as to avoid complexity in application deployment.
The common Spring Boot starter dependencies are as follows:
- spring-boot-starter-web
- spring-boot-starter-data-jpa
- spring-boot-starter-security
- spring-boot-starter-actuator
- spring-boot-starter-test
To find out the underlined Spring Framework dependencies, we can check the compile dependencies in maven repository
Spring Boot uses only Servlet 3 features to bootstrap an application.
Annotations
@Controller & @Service & @Repository
They are at different layers in the design from top to bottom. @Controller should be used to control which service needs to be applied for presentation. @Service should be used at the business logic level. @Repository should be used for JPA for object mapping (ORM) or JDBC for data access (DAO)
Normally DTOs (Data Transfer Object) are used at @Service layer for view/reporting and the pure plain database entity objects are for @Repository to retrieve rows from database.
@Entity @Query, @Transactional
JPA associated annotations
@Autowired
Explicit constructor is preferred compared to using @Autowired for dependency tracking and testing purpose.
@RestController & @ExceptionHandler @ControllerAdvice @ResponseStatus
Always use ResponseEntity<> for rest API return object. We will need to define an error handler method/class to use @ExceptionHandler or @ControllerAdvice.
If we just need a simple error response, such as 404, we could use @ResponseStatus to annotate our exception class which is derived from RuntimeException or HttpResonseException. This works even if the rest API does not return ResponseEntity.
Spring Boot Events
ApplicationReadyEvent
This event occurs when the application completes initialization and is ready for service, so it is used for data processing or job handling.
ContextClosedEvent
This event occurs when the applicationContext is closed, so it is used for data cleanup and job closing.