您可以做的是MyRestController
将结果包装成Response
这样:
@Controller
@RequestMapping(value = "/mycontroller")
public class MyRestController {
@Autowired
private MyController myController;
@RequestMapping(value = "/details")
public @ResponseBody Response<ServiceDetails> getServiceDetails() {
return new Response(myController.getServiceDetails(),"Operation OK");
}
}
此解决方案使您的原始MyController
代码独立于您的 REST 代码。看来您需要在类路径中包含 Jackson,以便 Spring 自动神奇地序列化为 JSON(有关详细信息,请参阅此内容)
编辑
看来你需要更通用的东西......所以这里有一个建议。
@Controller
@RequestMapping(value = "/mycontroller")
public class MyGenericRestController {
@Autowired
private MyController myController;
//this will match all "/myController/*"
@RequestMapping(value = "/{operation}")
public @ResponseBody Response getGenericOperation(String @PathVariable operation) {
Method operationToInvoke = findMethodWithRequestMapping(operation);
Object responseBody = null;
try{
responseBody = operationToInvoke.invoke(myController);
}catch(Exception e){
e.printStackTrace();
return new Response(null,"operation failed");
}
return new Response(responseBody ,"Operation OK");
}
private Method findMethodWithRequestMapping(String operation){
//TODO
//This method will use reflection to find a method annotated
//@RequestMapping(value=<operation>)
//in myController
return ...
}
}
并保持原来的“myController”几乎原样:
@Controller
public class MyController {
//this method is not expected to be called directly by spring MVC
@RequestMapping(value = "/details")
public ServiceDetails getServiceDetails() {
return new ServiceDetails("MyService");
}
}
主要问题:@RequestMappingMyController
可能需要被一些自定义注释替换(并适应findMethodWithRequestMapping
对此自定义注释执行自省)。