如何将XML配置转换为Java配置?基于Les Hazlewood的自定义Rest异常处理器
Got it, let's walk through translating Les Hazlewood's XML-based exception handling setup to Java configuration—perfect for your Spring Boot app that uses code-based config instead of XML. I’ve worked with this pattern before, so here’s a straightforward breakdown:
1. First, prep your custom exception handler class
If you haven’t already, your RestExceptionHandler class should include @ExceptionHandler methods to catch and format your specific exceptions. Here’s a typical example:
public class RestExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoundException ex, WebRequest request) { ErrorResponse error = new ErrorResponse( HttpStatus.NOT_FOUND.value(), ex.getMessage(), Instant.now() ); return new ResponseEntity<>(error, HttpStatus.NOT_FOUND); } // Add more @ExceptionHandler methods for other exceptions (like IllegalArgumentException, etc.) }
Note: ErrorResponse is a custom DTO you’ll define to carry error details—think status code, message, timestamp, etc.
2. Direct XML-to-Java translation: Register the ExceptionResolver bean
Les Hazlewood’s original XML config defines an ExceptionHandlerExceptionResolver with message converters and your custom handler. To replicate this in Java, create a @Configuration class:
@Configuration public class RestExceptionConfig { @Bean public ExceptionHandlerExceptionResolver exceptionHandlerExceptionResolver() { ExceptionHandlerExceptionResolver resolver = new ExceptionHandlerExceptionResolver(); // Set up JSON message converter (matches the XML's <messageConverters> list) MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(); resolver.setMessageConverters(List.of(jacksonConverter)); // Attach your custom exception handler (same as XML's <exceptionHandlerAdvice>) resolver.setExceptionHandlerAdvice(new RestExceptionHandler()); // Optional: Set order if you have multiple resolvers (lower number = higher priority) resolver.setOrder(0); return resolver; } }
3. Spring Boot-friendly shortcut: Use @ControllerAdvice
Les Hazlewood’s XML predates the @ControllerAdvice annotation, which is now the preferred, more concise approach in Spring Boot. This eliminates the need to manually register the resolver entirely:
Update your exception handler with @ControllerAdvice
@ControllerAdvice public class RestExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoundException ex, WebRequest request) { ErrorResponse error = new ErrorResponse( HttpStatus.NOT_FOUND.value(), ex.getMessage(), Instant.now() ); return new ResponseEntity<>(error, HttpStatus.NOT_FOUND); } // Override parent methods to customize default Spring exceptions (like validation errors) @Override protected ResponseEntity<Object> handleMethodArgumentNotValid( MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request ) { List<String> validationErrors = ex.getBindingResult() .getFieldErrors() .stream() .map(FieldError::getDefaultMessage) .collect(Collectors.toList()); ErrorResponse error = new ErrorResponse( status.value(), "Validation failed", validationErrors, Instant.now() ); return new ResponseEntity<>(error, status); } }
With this setup, Spring Boot automatically detects the @ControllerAdvice bean and applies its exception handlers to all your controllers—no extra config class required.
Quick Tips
- If your original XML had additional properties (like custom message converters or resolver ordering), you can set those directly on the
ExceptionHandlerExceptionResolverbean in the Java config. - Ensure your
ErrorResponseclass is properly annotated for JSON serialization (Jackson handles this out of the box if you’re using the Spring Boot Web starter).
内容的提问来源于stack exchange,提问作者Eniss

