[英]ExceptionHandlerExceptionResolver always returns 200 response code in Spring 5
[英]How to declare ExceptionHandlerExceptionResolver in Java code?
我正在閱讀這篇文章ExceptionHandler in Spring MVC ,我不明白為什么擴展ExceptionHandlerExceptionResolver
的類沒有任何注釋。
應該是豆子吧? 所以它必須用@Component
(或者可能是@Service
,但我不確定它是否屬於服務層)注釋或其他東西進行注釋?
那么為什么它沒有任何注釋以及 Spring 如何知道它是一個 bean 並且應該使用它呢?
您必須手動將處理程序添加到處理程序列表中(在下面的示例中,我使用了 SIMpleMappingExceptionsResolver,但您可以使用自己的實現):
package eu.anastasis.readingtrainer.configuration;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
@Configuration
@EnableWebMvc
public class ConfigurationAdapter extends WebMvcConfigurerAdapter {
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
exceptionResolvers.add(new SimpleMappingExceptionResolver());
}
}
請注意,通過這種方式,您可以覆蓋您可能設置的任何 @ControllerAdvice + @ExceptionHandler (我不知道如何結合這兩種策略)。
正如對@Andrea Pegoretti答案的更新一樣,在 Spring 5.XX 中,不推薦使用 WebMvcConfigurerAdapter,而是使用 WebMvcConfigurer 接口; 請參閱此 鏈接了解更多詳情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.