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.
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
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
Alternatively, disable the exception handler while keeping other library features:
api-response.enabled=false
- Since:
- 1.0.0
- Version:
- 1.3.0
- Author:
- Pasindu OG
- See Also:
-
GlobalExceptionHandlerAutoConfiguration
-
Constructor Summary
ConstructorsConstructorDescriptionDefault constructor for ApiResponseAutoConfiguration. -
Method Summary
Modifier and TypeMethodDescriptionRegisters theGlobalExceptionHandleras a Spring bean for automatic exception handling.org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizerConfigures strict JSON deserialization with opt-in security features via field-level annotations.
-
Constructor Details
-
ApiResponseAutoConfiguration
public ApiResponseAutoConfiguration()Default constructor for ApiResponseAutoConfiguration.This constructor is automatically invoked by Spring's dependency injection container during application startup when autoconfiguration is enabled.
-
-
Method Details
-
apiResponseAdvisor
Registers theGlobalExceptionHandleras a Spring bean for automatic exception handling.The handler provides comprehensive centralized exception management using Spring's
RestControllerAdvicemechanism, automatically converting 10 different types of exceptions to RFC 9457 ProblemDetail responses.Exception Coverage:
- General exceptions (500 Internal Server Error)
- Validation errors with field-level details (400 Bad Request)
- Type mismatch errors (400 Bad Request)
- Malformed JSON requests (400 Bad Request)
- Missing required parameters (400 Bad Request)
- 404 Not Found errors
- 405 Method Not Allowed
- 415 Unsupported Media Type
- Null pointer exceptions (500 Internal Server Error)
- Custom ApiException instances (custom status codes)
Features:
- Automatic trace ID generation for all errors
- Consistent trace IDs between logs and responses
- RFC 9457 compliant error format
- Comprehensive SLF4J logging with appropriate severity levels
- Automatic timestamp inclusion in all error responses
- Returns:
- A new instance of
GlobalExceptionHandlerregistered as a Spring bean.
-
strictJsonCustomizer
@Bean public org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer strictJsonCustomizer()Configures strict JSON deserialization with opt-in security features via field-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 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
@XssCheck) - Opt-in String Trimming - Removes whitespace (requires
@AutoTrim)
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
Example:
// DTO Definition public class UserDTO { private String name; private String email; } // Valid Request {"name": "John", "email": "[email protected]"} // ✓ Success // Invalid Request (will be rejected with 400 Bad Request) {"name": "John", "email": "[email protected]", "isAdmin": true} // ✗ Unknown fieldFeature 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.Example:
public enum Status { ACTIVE, INACTIVE, PENDING } // All these are accepted and map to Status.ACTIVE: {"status": "ACTIVE"} // ✓ Original {"status": "active"} // ✓ Lowercase {"status": "Active"} // ✓ Title case {"status": "AcTiVe"} // ✓ Mixed caseFeature 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 annotated with@XssCheck. This provides fail-fast security that prevents malicious content from ever entering your system.Default Behavior (No Annotation): Fields are NOT validated for HTML tags
With @XssCheck Annotation: HTML tags are detected and rejected
Detection Mechanism:
- Uses regex pattern:
(?s).*<\s*[a-zA-Z/!].* - Detects opening tags:
<script>,<img>,<div> - Detects closing tags:
</div>,</script> - Detects special tags:
<!DOCTYPE>,<!--comment--> - Works across multiple lines (DOTALL mode enabled)
Security Advantage: Unlike HTML escaping (which transforms
<to<), this approach rejects the request entirely. This prevents:- Stored XSS attacks
- DOM-based XSS attacks
- Second-order injection vulnerabilities
- Encoding bypass attempts
Example:
public class CommentDTO { @XssCheck private String content; // XSS validated private String commentId; // NOT validated (no annotation) } // Valid Requests (for content field with @XssCheck) {"content": "Hello World"} // ✓ Plain text {"content": "Price: $100 < $200"} // ✓ Comparison operators (no tag) {"content": "2 + 2 = 4"} // ✓ Math expressions // Invalid Requests (throws IllegalArgumentException) {"content": "<script>alert('XSS')</script>"} // ✗ Script injection {"content": "<img src=x onerror=alert(1)>"} // ✗ Image XSS {"content": "Hello<br>World"} // ✗ HTML tags {"content": "<!--comment-->"} // ✗ HTML comments {"content": "<!DOCTYPE html>"} // ✗ DOCTYPE declarationFeature 4: Opt-in String Trimming with @AutoTrim
Automatically removes leading and trailing whitespace from string fields annotated with
@AutoTrim, improving data quality and preventing common user input errors. Fields without the annotation preserve their original whitespace.Default Behavior (No Annotation)
By default, string fields preserve all whitespace:
public class UserDTO { private String username; // NOT trimmed (no annotation) private String email; // NOT trimmed (no annotation) } // Input → Output {"username": " john "} → {"username": " john "} {"email": " [email protected] "} → {"email": " [email protected] "}Opt-in with @AutoTrim Annotation
The
AdvancedStringDeserializerimplements context-aware deserialization usingValueDeserializer.createContextual(DeserializationContext, BeanProperty). When it detects the@AutoTrimannotation on a field, it creates a specialized deserializer instance with trimming enabled.Use Cases for @AutoTrim:
- User Input Fields: Names, emails, addresses where whitespace is unwanted
- Search Queries: Remove accidental spaces from user inputs
- Usernames: Ensure consistent formatting without extra spaces
- Reference Numbers: IDs, codes that should not have whitespace
Example:
public class LoginDTO { @AutoTrim private String username; // Trimmed: " admin " → "admin" private String password; // NOT trimmed: " pass123 " → " pass123 " } public class ProductDTO { @AutoTrim private String name; // Trimmed private String description; // NOT trimmed: preserves formatting }Combining Both Annotations
You can use both annotations together for fields that need both trimming and XSS validation:
public class SecureDTO { @AutoTrim @XssCheck private String cleanInput; // First trimmed, then XSS-validated } // These will be rejected (after trimming): {"cleanInput": " <script>alert(1)</script> "} // ✗ XSS attempt blocked {"cleanInput": " <img src=x> "} // ✗ HTML tag blockedImplementation Details
This method registers an inner class
AdvancedStringDeserializerthat extendsStdScalarDeserializer<String>. The deserializer operates in different modes based on field annotations:- Default Mode: No processing (preserves original value)
- Trim Mode:
shouldTrim = truewhen@AutoTrimis present - XSS Mode:
shouldXssCheck = truewhen@XssCheckis present - Combined Mode: Both trimming and validation when both annotations present
The
createContextual()method inspects each field's annotations during deserialization context creation and returns an appropriately configured deserializer instance.Global Application Scope
As a
JsonMapperBuilderCustomizerbean, these settings are automatically applied to Spring Boot's defaultObjectMapper, affecting:- All
@RequestBodydeserialization in REST controllers - All
@ResponseBodyserialization - WebSocket message handling
- Spring Data REST endpoints
- Spring Cloud Feign clients
- Any component using the autoconfigured ObjectMapper
Null Value Handling
Null values are preserved and never converted to empty strings:
{"name": null} → name = null (not "") {"name": ""} → name = "" {"name": " "} → name = " " (unchanged unless @AutoTrim is used)Disabling These Features
If you need to disable any of these features, you have three options:
- Exclude Auto-Configuration:
@SpringBootApplication(exclude = ApiResponseAutoConfiguration.class) public class Application { } - Override with @Primary Bean:
@Configuration public class CustomConfig { @Bean @Primary public JsonMapperBuilderCustomizer myCustomizer() { return builder -> { // Your custom configuration }; } } - Use Application Properties:
spring.autoconfigure.exclude=io.github.og4dev.config.ApiResponseAutoConfiguration
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:
-