不推荐使用WebMvcConfigurerAdapter类型

alv*_*ter 102 java spring spring-mvc

我只是迁移到spring mvc版本5.0.1.RELEASE但突然在eclipse中STS WebMvcConfigurerAdapter被标记为已弃用

public class MvcConfig extends WebMvcConfigurerAdapter {
  @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
        // to serve static .html pages...
        registry.addResourceHandler("/static/**").addResourceLocations("/resources/static/");
    }
  ....
  }
Run Code Online (Sandbox Code Playgroud)

我怎么能删除这个!

Plo*_*log 200

从Spring 5开始,您只需要实现接口WebMvcConfigurer:

public class MvcConfig implements WebMvcConfigurer {
Run Code Online (Sandbox Code Playgroud)

这是因为Java 8在接口上引入了默认方法,涵盖了WebMvcConfigurerAdapter类的功能

看这里:

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/WebMvcConfigurerAdapter.html

  • 将转换器添加到列表中,会关闭默认转换器注册。通过首先调用 super.configureMessageConverters(converters) 您可能希望保留默认转换器。要在不影响默认注册的情况下简单地添加转换器,请考虑使用方法 `extendMessageConverters(java.util.List)` (https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web /servlet/config/annotation/WebMvcConfigurer.html#extendMessageConverters-java.util.List-) 代替。 (3认同)

Ani*_*ade 6

我一直在研究Springfox现在称为Swagger的等效文档库,发现在Spring 5.0.8(目前正在运行)中,接口WebMvcConfigurer已由类WebMvcConfigurationSupportclass 实现,我们可以直接对其进行扩展。

import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

public class WebConfig extends WebMvcConfigurationSupport { }
Run Code Online (Sandbox Code Playgroud)

这就是我用来设置资源处理机制的方式,如下所示:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");

    registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
}
Run Code Online (Sandbox Code Playgroud)