WebMvcConfigurerAdapter 不工作

WebMvcConfigurerAdapter does not work

这是我正在处理的 WebConfig 代码:

package hello.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/greeting").setViewName("greeting");
    }
}

这是我的 Application.class

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@SpringBootApplication
public class Application extends SpringBootServletInitializer{

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

}

这似乎是一个 spring 引导问题,这些 class 方法在某些系统中没有被调用。相应的问题报告在: https://github.com/spring-projects/spring-boot/issues/2870

我的问题是,我们能否将在此 class 中映射的资源映射到此 class 之外作为临时解决方法?

如果是,我们该怎么做?

更新: 根据 Andy Wilkinson 的建议,我删除了 @EnableWebMvc 并且演示应用程序开始运行。然后我试着一个一个地剥离项目文件,看看错误在什么时候消失了。我发现我在项目中有两个 classes,一个是从 WebMvcConfigurationSupport 扩展而来的,第二个是 WebMvcConfigurerAdapter 扩展而来的。从项目中删除前者 class 修复了错误。

我想知道的是,为什么会这样?其次,为什么不是所有系统都出现这个错误?

问题是 WebConfigconfig 包中,而 Applicationhello 包中。 @SpringBootApplication on Application 启用组件扫描声明它的包和该包的子包。在这种情况下,这意味着 hello 是组件扫描的基础包,因此,永远找不到 config 包中的 WebConfig

为了解决这个问题,我将 WebConfig 移动到 hello 包或子包中,例如 hello.config.

您对 GitHub 的最新更新已将 WebConfig 从扩展 WebMvcConfigurerAdapter 更改为扩展 WebMvcConfigurationSupportWebMvcConfigurationSupport 是由 @EnableWebMvc 导入的 class,因此用 @EnableWebMvc 注释 class 并扩展 WebMvcConfigurationSupport 将配置两次。您应该像以前一样返回扩展 WebMvcConfigurerAdapter