我有以下控制器(注意其配置方式):
@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());
}
}
但是,当我在真实的应用程序中运行相同的东西时,当我在浏览器中尝试该请求时,它会为GET请求提供404。
奇怪的是,当向其发出POST请求时,SAME /execute
可以工作。正如您在上面看到的那样,POST和GET之间的动态映射非常相似。
我在这里做什么错了?