spring - Spring MVC 动态配置获取 404 但与 MockMVC 一起使用
问题描述
我有以下控制器(注意它的配置方式):
@Controller
public class MyController {
@Autowired
private RequestMappingHandlerMapping requestMappingHandlerMapping;
@PostConstruct
private void createRequestMapping() throws Exception {
RequestMappingInfo commandExecutionRequestMappingInfo =
RequestMappingInfo
.paths(endpointUri)
.methods(RequestMethod.POST)
.consumes(MediaType.APPLICATION_JSON_VALUE)
.produces(MediaType.APPLICATION_JSON_VALUE)
.build();
requestMappingHandlerMapping
.registerMapping(commandExecutionRequestMappingInfo, this,
MyController.class.getDeclaredMethod("execute", String.class));
RequestMappingInfo getAvailableCommandsRequestMappingInfo =
RequestMappingInfo
.paths(endpointUri)
.methods(RequestMethod.GET)
.build();
requestMappingHandlerMapping
.registerMapping(getAvailableCommandsRequestMappingInfo, this,
MyController.class
.getDeclaredMethod("getAvailableCommands", Model.class));
}
@ResponseBody
private String execute(@RequestBody String command) {
...
}
private String getAvailableCommands(Model model) {
model.addAttribute("docs", handlerDocs);
return "docs";
}
有一个docs.html
页面位于main/resources/templates/docs.html
.
当我使用 MockMvc 运行测试时,它会看到该页面的输出:
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class ApplicationConfig {
}
这是测试类:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApplicationConfig.class)
@AutoConfigureMockMvc
public class SpringRestCommanderTest {
@Autowired
private MockMvc mvc;
@Test
public void testGetAvailableCommands() throws Exception {
mvc.perform(get("/execute")).andDo(print());
}
}
然而,当我在一个真实的应用程序中运行同样的事情时,当我在浏览器中尝试它时,它给了我一个 404 的 GET 请求。
奇怪的是,/execute
当向它发出 POST 请求时,SAME 工作。正如您在上面看到的,POST 和 GET 之间的动态映射非常相似。
我在这里做错了什么?
解决方案
推荐阅读
- javascript - 链接接缝是什么意思?
- html - 垂直对齐中间,用于响应式顶部导航,没有固定高度
- python - 确保用户输入是整数并且在特定范围内的问题
- java - 无法在 Spring Boot 中将 Flyway 迁移与 postgresSQL 连接起来
- javascript - 如何使用计数器计时器在 React Native 中构建 OTP 组件并使用功能组件重新发送 otp 功能
- python - 用 return 语句去除多余的空间
- javascript - 如何找到两个日期之间的差异?
- swift - 如何从 Swift 中的同一字符串中获取字符串的特定部分?
- spring - 由于创建名为 adminHandlerMapping 的 bean 时出错,Spring-Boot-Admin 应用程序无法启动
- c# - Polly电路关闭时如何实现自定义方法