Class ApiResponseAutoConfiguration

java.lang.Object
io.github.og4dev.config.ApiResponseAutoConfiguration

@Configuration public class ApiResponseAutoConfiguration extends Object
Autoconfiguration class for the OG4Dev Spring API Response Library.

This configuration is automatically loaded by Spring Boot's autoconfiguration mechanism when the library is present on the classpath. It registers essential beans required for the library to function properly, including the comprehensive global exception handler and the automatic response wrapper.

Zero Configuration Required: Simply adding the library dependency enables all features automatically. No manual @ComponentScan or @Import annotations are needed.

What Gets Auto-Configured:

  • GlobalExceptionHandler - Comprehensive exception handling with RFC 9457 ProblemDetail format
    • 10 built-in exception handlers covering all common error scenarios
    • Automatic trace ID generation and logging
    • Validation error aggregation and formatting
    • Production-ready error messages
  • GlobalResponseWrapper - Automatic wrapping of controller responses (Opt-in via @AutoResponse)

How It Works:

Spring Boot 3.x+ automatically reads META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports and loads this configuration class during application startup.

Disabling Auto-Configuration:

If you need to customize or disable this autoconfiguration, you can exclude it in your main application class:


 @SpringBootApplication(exclude = ApiResponseAutoConfiguration.class)
 public class Application {
 public static void main(String[] args) {
 SpringApplication.run(Application.class, args);
 }
 }
 

Or in application.properties:

 spring.autoconfigure.exclude=io.github.og4dev.config.ApiResponseAutoConfiguration
 
Since:
1.0.0
Version:
1.4.0
Author:
Pasindu OG
See Also:
  • Constructor Details

    • ApiResponseAutoConfiguration

      public ApiResponseAutoConfiguration()
      Default constructor for ApiResponseAutoConfiguration.
  • Method Details

    • apiResponseAdvisor

      @Bean public GlobalExceptionHandler apiResponseAdvisor()
      Registers the GlobalExceptionHandler as a Spring bean for automatic exception handling.

      The handler provides comprehensive centralized exception management using Spring's RestControllerAdvice mechanism, automatically converting various exceptions to RFC 9457 ProblemDetail responses.

      * @return A new instance of GlobalExceptionHandler registered as a Spring bean.
    • globalResponseWrapper

      @Bean @ConditionalOnMissingBean public GlobalResponseWrapper globalResponseWrapper(tools.jackson.databind.ObjectMapper objectMapper)
      Registers the GlobalResponseWrapper as a Spring bean for automatic API response wrapping.

      This bean enables the opt-in @AutoResponse feature. When a REST controller or method is annotated with @AutoResponse, this wrapper automatically intercepts the outgoing payload and encapsulates it within the standardized ApiResponse<T> structure before it is written to the HTTP response body.

      Key Capabilities:

      • Zero Boilerplate: Eliminates the need to manually return ResponseEntity<ApiResponse<T>> from every controller method.
      • Status Code Preservation: Intelligently reads and preserves custom HTTP status codes set via @ResponseStatus (e.g., 201 Created).
      • Double-Wrap Prevention: Safely skips wrapping if the controller already returns an ApiResponse or ResponseEntity.
      • String Payload Support: Safely intercepts and serializes raw String returns using the injected ObjectMapper to prevent ClassCastException with Spring's native message converters.
      • Error Compatibility: Bypasses ProblemDetail and exception responses to maintain RFC 9457 compliance managed by GlobalExceptionHandler.

      Example Usage:

      
       @RestController
       @RequestMapping("/api/users")
       @AutoResponse // Enables automatic wrapping for all methods in this controller
       public class UserController {
       * @GetMapping("/{id}")
       public UserDto getUser(@PathVariable Long id) {
       // Simply return the DTO. It will be sent to the client as:
       // { "status": "Success", "content": { "id": 1, "name": "..." }, "timestamp": "..." }
       return userService.findById(id);
       }
       * @PostMapping
       @ResponseStatus(HttpStatus.CREATED)
       public UserDto createUser(@RequestBody UserDto dto) {
       // The 201 Created status will be preserved in the final ApiResponse
       return userService.create(dto);
       }
       }
       

      Note: This bean is conditionally loaded using @ConditionalOnMissingBean, allowing developers to easily override the default wrapping behavior by defining their own GlobalResponseWrapper bean.

      Parameters:
      objectMapper - The Jackson object mapper injected by Spring, used by the wrapper for explicit string serialization.
      Returns:
      A new instance of GlobalResponseWrapper registered as a Spring bean.
      Since:
      1.4.0
      See Also:
    • strictJsonCustomizer

      @Bean public org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer strictJsonCustomizer()
      Configures strict JSON deserialization with opt-in security features via field-level and class-level annotations.

      This bean customizer enhances Jackson's JSON processing with production-ready security and data quality features that can be selectively applied to specific fields or entire classes using the @AutoTrim and @XssCheck annotations. By default, fields are NOT trimmed or XSS-validated unless explicitly annotated.

      Overview of Features

      This configuration provides four critical layers of protection and data processing:

      1. Strict Property Validation - Prevents mass assignment attacks (automatic)
      2. Case-Insensitive Enum Handling - Improves API usability (automatic)
      3. Opt-in XSS Prevention - Blocks HTML/XML injection attacks (requires @XssCheck on field or class)
      4. Opt-in String Trimming - Removes whitespace (requires @AutoTrim on field or class)

      Feature 1: Strict Property Validation

      Enables DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES to reject JSON payloads containing unexpected fields. This prevents three critical security issues:

      • Mass Assignment Vulnerabilities: Attackers cannot inject fields like isAdmin: true
      • Data Injection Attacks: Prevents modification of unintended database fields
      • Client Errors: Detects typos early, preventing silent data loss

      Feature 2: Case-Insensitive Enum Handling

      Enables MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS for flexible enum deserialization. Clients can send enum values in any case format, improving API usability without compromising type safety or security.

      Feature 3: Opt-in XSS Prevention with @XssCheck

      Registers a custom StdScalarDeserializer (AdvancedStringDeserializer) that performs automatic HTML/XML tag detection and rejection at the deserialization layer for fields or classes annotated with @XssCheck. This provides fail-fast security that prevents malicious content from ever entering your system.

      Feature 4: Opt-in String Trimming with @AutoTrim

      Automatically removes leading and trailing whitespace from string fields or entire classes annotated with @AutoTrim, improving data quality and preventing common user input errors.

      Combining Features (Class and Field Level)

      You can combine these annotations at both the class and field levels. Class-level annotations apply to all string fields within the class automatically:

      
       @AutoTrim // Automatically trims ALL strings in this class
       public class SecureDTO {
       @XssCheck
       private String cleanInput;  // Both trimmed (from class scope) and XSS-validated
       * private String email;       // Only trimmed (from class scope)
       }
       

      Implementation Details

      This method registers an inner class AdvancedStringDeserializer that extends StdScalarDeserializer<String>. The deserializer operates in different modes based on annotations:

      • Default Mode: No processing (preserves original value)
      • Trim Mode: shouldTrim = true when @AutoTrim is present on the field or class
      • XSS Mode: shouldXssCheck = true when @XssCheck is present on the field or class
      • Combined Mode: Both trimming and validation when both annotations are present

      The createContextual() method inspects each field's annotations, as well as its declaring class's annotations, during deserialization context creation and returns an appropriately configured deserializer instance.

      Null Value Handling

      Null values are preserved and never converted to empty strings.

      Performance Considerations

      The regex validation and trimming operations are highly optimized and add negligible overhead (typically <1ms per request). The contextual deserializer is created once per field during mapper initialization, not on every request, ensuring optimal runtime performance.

      Returns:
      A JsonMapperBuilderCustomizer that configures strict JSON processing with opt-in string validation via @XssCheck, opt-in trimming via @AutoTrim, unknown property rejection, and case-insensitive enum handling.
      Since:
      1.1.0
      See Also:
      • DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
      • MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS
      • AutoTrim
      • XssCheck
      • JsonMapperBuilderCustomizer
      • StdScalarDeserializer
      • ValueDeserializer.createContextual(DeserializationContext, BeanProperty)