Spring Boot
1.0 Annotation
-
@SpringBootApplication=@ComponentScan+@EnableAutoConfiguration+@Configuration
1.1 Java bean validations
# Entity
@NotNull
@Size
@Min
@Max
@Email
@NotEmpty
@NotBlank
# POM
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
# Exception Handler
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class ValidationHandler extends ResponseEntityExceptionHandler{
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach((error) ->{
String fieldName = ((FieldError) error).getField();
String message = error.getDefaultMessage();
errors.put(fieldName, message);
});
return new ResponseEntity<Object>(errors, HttpStatus.BAD_REQUEST);
}
}
2.1 Dispatcher Servlet?
-
DispatcherServlet acts as the Front Controller for Spring-based web applications.
- The job of the DispatcherServlet is to take an incoming URI and find the right combination of handlers
(generally methods on Controller classes) and views (generally JSPs) that combine to form the page or
resource that's supposed to be found at that location.
3.1 Goals
- Build Quickly
- Spring initializr
- Spring Boot Starter Projects
- Spring Boot Auto Configurations
- Spring Boot DevTools
- Be Production ready
- Logging
- Different configuration for different environments (profile,ConfigurationProperties)
- Monitoring (Spring Boot Actuator)
3.1.1 Spring Boot Starter
- spring-boot-starter-web
- org.springframework.boot:spring-boot-starter
- org.springframework.boot:spring-boot-starter-tomcat
- org.springframework.boot:spring-boot-starter-validation
- com.fasterxml.jackson.core:jackson-databind
- org.springframework:spring-web
- org.springframework:spring-webmvc
- spring-boot-starter-test
- spring-boot-starter-validation
- spring-boot-starter-security
- spring-boot-starter-data-jpa
- spring-boot-starter-tomcat
- spring-boot-starter-logging
3.1.2 Spring Boot Auto Configurations
- Automated configuration for your app , decided based on
- which frameworks are in the Class path?
- what is the existing configuration (Annotation ect)?
- Eg: Spring Boot Starter Web
- Dispatcher Servlet - (DispatcherServletAutoConfiguration)
- Default Error page - (ErrorMvcAutoConfiguration)