Class ApiResponseAutoConfiguration
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:
-
GlobalExceptionHandlerGlobalResponseWrapperAutoConfiguration
-
Constructor Summary
ConstructorsConstructorDescriptionDefault constructor for ApiResponseAutoConfiguration. -
Method Summary
Modifier and TypeMethodDescriptionRegisters theGlobalExceptionHandleras a Spring bean for automatic exception handling.globalResponseWrapper(tools.jackson.databind.ObjectMapper objectMapper) Registers theGlobalResponseWrapperas a Spring bean for automatic API response wrapping.org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizerConfigures strict JSON deserialization with opt-in security features via field-level and class-level annotations.
-
Constructor Details
-
ApiResponseAutoConfiguration
public ApiResponseAutoConfiguration()Default constructor for ApiResponseAutoConfiguration.
-
-
Method Details
-
apiResponseAdvisor
Registers theGlobalExceptionHandleras a Spring bean for automatic exception handling.The handler provides comprehensive centralized exception management using Spring's
* @return A new instance ofRestControllerAdvicemechanism, automatically converting various exceptions to RFC 9457 ProblemDetail responses.GlobalExceptionHandlerregistered as a Spring bean. -
globalResponseWrapper
@Bean @ConditionalOnMissingBean public GlobalResponseWrapper globalResponseWrapper(tools.jackson.databind.ObjectMapper objectMapper) Registers theGlobalResponseWrapperas a Spring bean for automatic API response wrapping.This bean enables the opt-in
@AutoResponsefeature. When a REST controller or method is annotated with@AutoResponse, this wrapper automatically intercepts the outgoing payload and encapsulates it within the standardizedApiResponse<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
ApiResponseorResponseEntity. - String Payload Support: Safely intercepts and serializes raw
Stringreturns using the injectedObjectMapperto preventClassCastExceptionwith Spring's native message converters. - Error Compatibility: Bypasses
ProblemDetailand exception responses to maintain RFC 9457 compliance managed byGlobalExceptionHandler.
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 ownGlobalResponseWrapperbean.- Parameters:
objectMapper- The Jackson object mapper injected by Spring, used by the wrapper for explicit string serialization.- Returns:
- A new instance of
GlobalResponseWrapperregistered as a Spring bean. - Since:
- 1.4.0
- See Also:
- Zero Boilerplate: Eliminates the need to manually return
-
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
@AutoTrimand@XssCheckannotations. 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:
- Strict Property Validation - Prevents mass assignment attacks (automatic)
- Case-Insensitive Enum Handling - Improves API usability (automatic)
- Opt-in XSS Prevention - Blocks HTML/XML injection attacks (requires
@XssCheckon field or class) - Opt-in String Trimming - Removes whitespace (requires
@AutoTrimon field or class)
Feature 1: Strict Property Validation
Enables
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIESto 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_ENUMSfor 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
AdvancedStringDeserializerthat extendsStdScalarDeserializer<String>. The deserializer operates in different modes based on annotations:- Default Mode: No processing (preserves original value)
- Trim Mode:
shouldTrim = truewhen@AutoTrimis present on the field or class - XSS Mode:
shouldXssCheck = truewhen@XssCheckis 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
<1msper request). The contextual deserializer is created once per field during mapper initialization, not on every request, ensuring optimal runtime performance.- Returns:
- A
JsonMapperBuilderCustomizerthat 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:
-