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.1.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 automatic string validation and trimming.
-
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 automatic string validation and trimming.This bean customizer enhances Jackson's JSON processing with three critical security and data quality features that are automatically applied to all API endpoints:
1. Strict Property Validation
Enables
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIESto reject JSON payloads containing unexpected fields, preventing:- Mass assignment vulnerabilities
- Data injection attacks
- Client-side typos that could cause silent data loss
Example: If your DTO expects
{name, email}, sending{name, email, isAdmin}will result in a 400 Bad Request error.2. Case-Insensitive Enum Handling
Enables
MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMSfor flexible enum deserialization, allowing clients to send enum values in any case format (e.g., "ACTIVE", "active", "Active" all map to the same enum constant). This improves API usability without compromising type safety.3. Automatic HTML Tag Detection and Rejection
Registers a custom
StdDeserializerthat automatically:- Trims whitespace: Removes leading and trailing spaces from all string values
- Detects HTML tags: Uses regex pattern
.*<\s*[a-zA-Z/!].*to identify HTML/XML tags - Rejects malicious input: Throws
IllegalArgumentExceptionif HTML tags are detected - Preserves nulls: Null values remain null (not converted to empty strings)
Security Benefit: This provides automatic XSS prevention at the deserialization layer using a fail-fast approach. Unlike HTML escaping, this prevents malicious content from ever entering your system, providing stronger security guarantees.
Example behavior:
Valid: {"name": " John Doe "} → {"name": "John Doe"} Invalid: {"name": "<script>alert('XSS')</script>"} → Throws IllegalArgumentException: "Security Error: HTML tags or XSS payloads are not allowed in the request."Global Application
As a
JsonMapperBuilderCustomizerbean, these settings are automatically applied to Spring Boot's defaultObjectMapper, affecting:- All
@RequestBodydeserialization in REST controllers - All
@ResponseBodyserialization - WebSocket message handling
- Any component using the autoconfigured ObjectMapper
Disabling This Feature
If strict JSON validation or HTML tag rejection interferes with your use case (e.g., you need to accept HTML content), you can exclude this autoconfiguration or provide your own
JsonMapperBuilderCustomizerbean with higher precedence using@Primary.- Returns:
- A
JsonMapperBuilderCustomizerthat configures strict JSON processing with automatic string validation, HTML tag rejection, unknown property rejection, and case-insensitive enum handling. - Since:
- 1.1.0
- See Also:
-
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIESMapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMSJsonMapperBuilderCustomizer
-