WebMvcConfigurerAdapter 类型已弃用

2022-08-31 08:29:06

我刚刚迁移到春季mvc版本,但突然在eclipse STS WebMvcConfigurerAdapter被标记为已弃用5.0.1.RELEASE

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/");
    }
  ....
  }

我怎么能删除这个!


答案 1

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

public class MvcConfig implements WebMvcConfigurer {

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

请参阅此处:

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


答案 2

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

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

public class WebConfig extends WebMvcConfigurationSupport { }

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

@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/");
}

推荐