首页 > 解决方案 > 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 之间的动态映射非常相似。

我在这里做错了什么?

标签: springspring-mvcspring-boot

解决方案


推荐阅读