java - Spring : Using Interface as RequestBody and returning the right class

标签 java spring interface controller

我正在尝试在 Spring Controller 中使用接口(interface),但在实例化正确的类时遇到了问题。

我有以下方法:

@RequestMapping(value="/settings/features/{feature}", method=RequestMethod.POST, produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseEntityWrapper setFeatureSettings(
        HttpServletRequest request,
        @PathVariable Feature feature,
        @RequestBody IFeatureSettings featureSettings,
        HttpServletResponse response
        ) {
           ...
        }

我有几个实现 IFeatureSettings 的类,我需要为输入实例化正确的类。我可以通过查看功能(它是一个枚举)知道哪个是正确的类。因此,对于功能 A,我将使用 AFeatureSettingsImpl,对于功能 B,我将使用 BFeatureSettingsImpl。

理想情况下,会有某种方式介入中间并说:这次,用数据填充类 AFeatureSettingsImpl 并将其作为接口(interface)实现返回。

我一直在查看 HandlerMethodArgumentResolver,这听起来是正确的方法,但我不确定如何执行此操作。我需要访问 feature 参数,希望在我得到我的解决代码之前解决它(或者我需要自己解决它)。

最佳答案

如何编写另一个将 featurebodyObject 作为参数的方法?

有点像

private final IFeatureSettings getFeatureImpl(Feature feature, Object bodyObject) {
switch(feature) {
case a: return new AFeatureSettingsImpl;
...
   }
}

顺便说一句,我真的不知道你想要的中间的东西是否存在。

关于java - Spring : Using Interface as RequestBody and returning the right class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23883750/

相关文章:

java - 查找 int 数组是否包含数字的最快方法

java - Controller 处理程序方法支持的返回类型

java - maven部署配置信息到tomcat

spring - 如何建议 (AOP) spring webflux web 处理程序捕获和转换 react 性错误

java - Comparable<T> 和compareTo

html - 如何更改我的 Mercurial Web 界面方面

java - 删除字符串中重复字符的函数

JavaFX:创建垂直菜单功能区

java - 使用 SWTBot 自动化第三方应用程序。是否可以?

c# - IList<InterfaceType> 到 List<ImplementsInterfaceType>?