Подтвердить что ты не робот

Тип WebMvcConfigurerAdapter устарел

Я просто 5.0.1.RELEASE на весеннюю версию 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/");
    }
  ....
  }

Как я могу удалить это!

4b9b3361

Ответ 1

Начиная с весны 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, которая называется Springfox и я обнаружил, что в 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/");
}

Ответ 3

Весной каждый запрос будет проходить через DispatcherServlet. Чтобы избежать запроса статического файла через DispatcherServlet (Front contoller), мы настраиваем содержимое MVC Static.

Весна 3.1. представил ResourceHandlerRegistry для настройки ResourceHttpRequestHandlers для обслуживания статических ресурсов из пути к классам, WAR или файловой системы. Мы можем программно настроить ResourceHandlerRegistry внутри нашего класса конфигурации веб-контекста.

  • мы добавили шаблон /js/** в ResourceHandler, включив в него foo.js расположенный в каталоге webapp/js/
  • мы добавили шаблон /resources/static/** в ResourceHandler, включив в foo.html ресурс foo.html расположенный в каталоге webapp/resources/
@Configuration
@EnableWebMvc
public class StaticResourceConfiguration implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("WebMvcConfigurer - addResourceHandlers() function get loaded...");
        registry.addResourceHandler("/resources/static/**")
                .addResourceLocations("/resources/");

        registry
            .addResourceHandler("/js/**")
            .addResourceLocations("/js/")
            .setCachePeriod(3600)
            .resourceChain(true)
            .addResolver(new GzipResourceResolver())
            .addResolver(new PathResourceResolver());
    }
}

Конфигурация XML

<mvc:annotation-driven />
  <mvc:resources mapping="/staticFiles/path/**" location="/staticFilesFolder/js/"
                 cache-period="60"/>

Spring Boot MVC Static Content, если файл находится в папке WARPS webapp/resources.

spring.mvc.static-path-pattern=/resources/static/**

Ответ 4

Используйте 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();
    }

}