背景
我在弹簧引导(1.4.0.RELEASE),其不应该被连接到数据源,因此,需要已经简单REST API接受一个对象并用它以相同的方法返回另一个对象(接口类型)。这(种)不寻常的行为导致我使用RequestMethod.POST
既能够有@RequestBody和@ResponseBody:弹簧引导 - REST方法返回接口
@RestController
public class SomeController {
@RequestMapping(value = "/path", method = RequestMethod.POST)
public ResponseEntity<SomeInterface> someMethod(@RequestBody SomeClass obj) {
SomeInterface toReturn = createSomeInterface(...);
return new ResponseEntity<>(toReturn, HttpStatus.OK);
}
}
我也有一个Test
方法:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SomeApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SomeControllerTests {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void testSomeMethod() {
SomeClass toPost = createPostObj();
ResponseEntity<SomeInterface> respons = this.restTemplate.postForEntity("/path", toPost, SomeInterface.class);
assertEquals(HttpStatus.OK, respons.getStatusCode());
assertNotEquals(null, respons.getBody());
}
}
然而,这抛出:
org.springframework.http.converter.HttpMessageNotReadableException:
Could not read document:
Can not construct instance of SomeInterface:
abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
问
假设都SomeInterface
和SomeClass
是财物等API的和不能改变的,这是可能做到?
注意
我已经尽力了SomeInterface
包装成一个类没有成功:
public class Wrapper {
SomeInterface obj;
// getter and setter ...
}
'SomeInterface toReturn = createSomeInterface(...);'你有SomeInterface的实现?因为你不能实例化一个java接口。 –
@IssamELATIF存在一个实现'SomeInterfaceImpl',它是外部API yes的一部分。 –