背景
我在彈簧引導(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的一部分。 –