我正在尝试在 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 参数,希望在我得到我的解决代码之前解决它(或者我需要自己解决它)。
最佳答案
如何编写另一个将 feature
和 bodyObject
作为参数的方法?
有点像
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/