dhb*_*lah 6 java spring exception-handling
我正在阅读这篇文章:http : //spring.io/blog/2013/11/01/exception-handling-in-spring-mvc##extending-exceptionhandlerexceptionresolver,我不明白为什么类扩展ExceptionHandlerExceptionResolver没有任何对其的注释。应该是豆吧?所以它必须用@Component(或者可能@Service,但我不确定它是否属于服务层)注释或其他东西进行注释?那么为什么它没有任何注释,那么 spring 如何知道它是一个 bean 并且应该使用它呢?
小智 8
您必须手动将处理程序添加到处理程序列表中(在下面的示例中,我使用了 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());
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,通过这种方式,您可以覆盖您可能设置的任何 @ControllerAdvice + @ExceptionHandler (我不知道如何结合这两种策略)。
小智 5
正如对 @ Andrea Pegoretti答案的更新一样,在 Spring 5.XX 中,不推荐使用 WebMvcConfigurerAdapter,而是使用 WebMvcConfigurer 接口;请参阅此链接了解更多详细信息。
| 归档时间: |
|
| 查看次数: |
8791 次 |
| 最近记录: |