gpt4 book ai didi

spring - WebMvcConfigurerAdapter 不起作用

转载 作者:行者123 更新时间:2023-12-02 07:03:41 24 4
gpt4 key购买 nike

这是我正在处理的 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-boot 问题。相应的问题报告于: https://github.com/spring-projects/spring-boot/issues/2870

我的问题是,我们可以将此类中映射的资源映射到此类之外,作为临时解决方法吗?

如果是,我们该怎么做?

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

我想知道的是,为什么会发生这种情况?其次,为什么这个错误不是在所有系统上都出现?

最佳答案

问题是 WebConfig位于 config包和Application位于 hello包裹。 @SpringBootApplicationApplication启用对其声明的包及其子包的组件扫描。在这种情况下,这意味着 hello是组件扫描的基础包,因此 WebConfigconfig从未找到包。

为了解决这个问题,我会移动WebConfig进入hello包或子包,例如 hello.config .

您在 GitHub 上的最新更新已更改 WebConfig从延伸WebMvcConfigurerAdapter延伸WebMvcConfigurationSupportWebMvcConfigurationSupport@EnableWebMvc 导入的类所以用 @EnableWebMvc 注释你的类并延伸WebMvcConfigurationSupport将配置两次。您应该返回扩展 WebMvcConfigurerAdapter就像以前一样。

关于spring - WebMvcConfigurerAdapter 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30910642/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com