这是我正在处理的 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
我的问题是,我们可以将此类中映射的资源映射到此类之外,作为临时解决方法吗?
如果是,我们该怎么做?
更新:按照安迪·威尔金森的建议,我删除了
@EnableWebMvc
,演示应用程序开始工作。然后我尝试将项目文件一一剥离,看看错误在什么时候消失。我发现我的项目中有两个类,一个是从 WebMvcConfigurationSupport
扩展的,第二个是从 WebMvcConfigurerAdapter
扩展的。从项目中删除前一个类修复了错误。
我想知道的是,为什么会发生这种情况?其次,为什么这个错误不是在所有系统上都出现?
问题是
WebConfig
在 config
包中,而 Application
在 hello
包中。 @SpringBootApplication
上的 Application
启用对声明它的包及其子包的组件扫描。在这种情况下,这意味着 hello
是组件扫描的基础包,因此,永远找不到 WebConfig
包中的 config
。
为了解决这个问题,我会将
WebConfig
移动到 hello
包或子包中,例如 hello.config
。
您在 GitHub 上的最新更新将
WebConfig
从扩展 WebMvcConfigurerAdapter
更改为扩展 WebMvcConfigurationSupport
。 WebMvcConfigurationSupport
是由 @EnableWebMvc
导入的类,因此用 @EnableWebMvc
注释你的类并扩展 WebMvcConfigurationSupport
将配置两次。您应该像以前一样继续延长 WebMvcConfigurerAdapter
。
在我的 Spring Boot 应用程序中,它只需要对 Contorller 类添加一个注释 @CrossOrigin 。
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/add")
public String addUser(@RequestBody User user){
userService.addUser(user);
return "Success add user.";
}
}