WebMvcConfigurerAdapter 已过时

不推荐使用WebMvcConfigurerAdapter类型 (3)

我只是迁移到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/");
    }
  ....
  }

我怎么能删除这个!

从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


使用 org.springframework.web.servlet.config.annotation.WebMvcConfigurer

使用Spring Boot 2.1.4.RELEASE(Spring Framework 5.1.6.RELEASE),这样做

package vn.bkit;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; // Deprecated.
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
public class MvcConfiguration implements WebMvcConfigurer {

    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/");
        resolver.setSuffix(".html");
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

}

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

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/");
}
发布了78 篇原创文章 · 获赞 79 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/jack1liu/article/details/104355044