DEV Community

Code Green
Code Green

Posted on

Spring Boot Cheat Sheet

Spring Boot Cheat Sheet

Annotations

Annotation Description Example
@SpringBootApplication Marks a class as a Spring Boot application. Enables auto-configuration and component scanning. @SpringBootApplication
@RestController Indicates that a class provides RESTful endpoints. It combines @Controller and @ResponseBody annotations. @RestController
@RequestMapping Maps HTTP requests to handler methods of RESTful controllers. @RequestMapping("/api")
@Autowired Injects dependencies into a Spring bean. It can be used for constructor, setter, or field injection. @Autowired private MyService myService;
@Component Indicates that a class is a Spring-managed component. It is automatically detected during component scanning. @Component
@Repository Marks a class as a Spring Data repository. It handles data access and persistence logic. @Repository
@Service Marks a class as a service component in the business layer. It is used to separate business logic from presentation logic. @Service
@Configuration Indicates that a class provides bean definitions. It is used along with @bean to define beans in Java-based configuration. @Configuration
@Value Injects values from properties files or environment variables into Spring beans. @Value("${my.property}") private String property;

Control Flow

  1. Initialization: Spring Boot starts by loading application properties and auto-configuring beans.
  2. Component Scanning: Spring scans for components like controllers, services, and repositories.
  3. Bean Creation: Spring creates beans and resolves dependencies using dependency injection.
  4. Request Handling: Incoming HTTP requests are mapped to controller methods based on request mappings.
  5. Execution: Controller methods handle requests, interact with services, and return responses.
  6. Response Rendering: Spring converts method return values to appropriate HTTP responses (e.g., JSON).

Recommended Folder Structure

src
├── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ ├── controller
│ │ │ └── MyController.java
│ │ ├── service
│ │ │ └── MyService.java
│ │ └── Application.java
│ └── resources
│ ├── application.properties
│ └── templates
│ └── index.html
└── test
└── java
└── com
└── example
└── controller
└── MyControllerTest.java

Error Handling in Spring Boot Cheat Sheet

Error handling is a critical aspect of building robust applications. Spring Boot provides several mechanisms for handling errors and exceptions gracefully, ensuring a smooth user experience.

Types of Errors

  • Client Errors: Errors caused by invalid client requests, such as 400 Bad Request or 404 Not Found.
  • Server Errors: Errors occurring on the server-side, such as 500 Internal Server Error.
  • Validation Errors: Errors due to invalid input or data validation failures.

Error Handling Mechanisms

1. Controller Advice

  • @ControllerAdvice: An annotation used to define global exception handlers in Spring MVC.
  • @ExceptionHandler: An annotation used to handle specific exceptions within a controller advice.
  • Example:
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MyException.class)
    public ResponseEntity<ErrorResponse> handleMyException(MyException ex) {
        ErrorResponse response = new ErrorResponse("My error message");
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleException(Exception ex) {
        ErrorResponse response = new ErrorResponse("Internal server error");
        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
Enter fullscreen mode Exit fullscreen mode

ResponseEntityExceptionHandler

  • ResponseEntityExceptionHandler: A base class for handling common Spring MVC exceptions.
  • Overrides: Override methods like handleMethodArgumentNotValid, handleHttpMessageNotReadable, etc.
  • Example:
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
        MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
    ErrorResponse response = new ErrorResponse("Validation failed");
    return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
}

// Other overrides for handling specific exceptions

Enter fullscreen mode Exit fullscreen mode

3. Error Attributes

  • ErrorAttributes: Interface used to customize the content and format of error responses.
  • DefaultErrorAttributes: Default implementation provided by Spring Boot.

@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
    Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, includeStackTrace);
    errorAttributes.put("customAttribute", "Custom value");
    return errorAttributes;
}

}
Enter fullscreen mode Exit fullscreen mode

Using Properties Files

  • application.properties: Store application-wide properties like server port, database URL, etc.
  • Custom Properties Files: Define custom properties files for different environments (e.g., application-dev.properties).
  • Accessing Properties: Access properties using @Value annotation or Spring's Environment API.

Building Project

  • Maven: Run mvn clean install to build the project and generate an executable JAR.
  • Gradle: Run ./gradlew build to build the project and generate an executable JAR.

Additional Topics

  • Spring Boot Starters: Use starters to add dependencies and auto-configuration to your project.
  • Logging: Configure logging using Logback, Log4j, or Java Util Logging.
  • Error Handling: Implement global exception handling with @ControllerAdvice.
  • Testing: Write unit tests and integration tests using JUnit, Mockito, and SpringBootTest.

Top comments (1)

Collapse
 
codegreen profile image
Code Green

🌟 Exciting news! We now have an AWS Cloud Practitioner quiz app to help you prepare for the certification exam. Test your knowledge and boost your confidence!

👉 Download from PlayStore and start your journey today!