【问题标题】:How to declare ExceptionHandlerExceptionResolver in java code?如何在java代码中声明ExceptionHandlerExceptionResolver?
【发布时间】:2013-11-20 07:29:14
【问题描述】:

我正在阅读这篇文章:http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc##extending-exceptionhandlerexceptionresolver,但我不明白为什么扩展 ExceptionHandlerExceptionResolver 的类没有任何注释。应该是豆子吧?所以它必须用@Component(或者可能@Service,但我不确定它是否属于服务层)注解什么的注解?那么为什么它没有任何注释,那么 spring 如何知道它是一个 bean 并且应该使用它呢?

【问题讨论】:

    标签: java spring exception-handling


    【解决方案1】:

    您必须手动将您的处理程序添加到处理程序列表中(在下面的示例中,我使用了一个 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(我不知道如何结合这两种策略)。

    【讨论】:

      【解决方案2】:

      就像对@Andrea Pegoretti 答案的更新一样, 在 Spring 5.X.X WebMvcConfigurerAdapter 中已弃用,而是使用 WebMvcConfigurer 接口;详情请参考link

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-09-03
        • 2012-12-05
        • 1970-01-01
        • 2021-05-03
        • 1970-01-01
        • 2022-06-14
        • 1970-01-01
        相关资源
        最近更新 更多