在 spring boot 2.1.1 自动配置中不调用 addInterceptors

Ale*_*lex 2 interceptor spring-boot

我正在编写一个 spring-boot start,旨在为处理程序自动配置拦截器。主类如下所示:

@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties(MetricsProperties.class)
public class MetricsConfiguration implements WebMvcConfigurer {
    private static Logger logger = LoggerFactory.getLogger(MetricsConfiguration.class);

    private final MetricsProperties metricsProperties;

    public MetricsConfiguration(MetricsProperties properties) {
        this.metricsProperties = properties;
    }

    @Bean
    @Order(0)
    public MetricsCenter createMetricsCenter() {
        MetricsCenter metricsCenter = MetricsCenter.getInstance();
        metricsCenter.init(metricsProperties);
        return metricsCenter;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        logger.error("alex add");   // the log does not appear!!
        registry.addInterceptor(new MetricsInterceptor());
    }
}
Run Code Online (Sandbox Code Playgroud)

根据文件

https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-spring-mvc-auto-configuration

其中说:

如果您想保留 Spring Boot MVC 功能并添加额外的 MVC 配置(拦截器、格式化程序、视图控制器和其他功能),您可以添加您自己的 WebMvcConfigurer 类型的 @Configuration 类,但不添加 @EnableWebMvc。如果您希望提供 RequestMappingHandlerMapping、RequestMappingHandlerAdapter 或 ExceptionHandlerExceptionResolver 的自定义实例,您可以声明一个 WebMvcRegistrationsAdapter 实例来提供此类组件。

我按照文档说的做了,但是addInterceptors没有调用,我的拦截器没有配备spring mvc。

有人可以帮我离开这里吗?

谢谢。

小智 7

您可能有一个自定义@Configuration类(例如在您的 starter 的使用者中)扩展WebMvcConfigurationSupport类,在这种情况下,它需要完全控制并且您的WebMvcConfigurers 不会被调用。