2017-11-11 109 views
0

我正在構建一個Angular應用程序,它與使用Spring框架編寫的restful API進行通信。Spring框架中的Http post方法中傳遞層次對象

我的類層次結構是這樣的:

class Resource 
class FileResource extends Resource 
class DbResource extends Resource 
class DbFileResource extends DbResource 
class DbServerResource extends DbResource 

,我在我的例子POST請求,這套房DbServerResource在我的類層次發送這樣的JSON對象:

{ 
"resourceName": "Res2", 
"resourceType": "DB_SERVER", 
"dbms": "DB2", 
"dbName": "SHOP", 
"host": "<some ip>", 
"port": 50000, 
"userName": "user", 
"password": "password" 
} 

在我的控制器我有我有addResource方法:

@RequestMapping (method = RequestMethod.POST, value="/resource") 
private void addResource(@RequestBody Resource resource) 

和我有我打電話用instanceof檢索確切的對象的工作與工廠類:

public ResourceId getResourceId(Resource res){ 

    if (res== null){ 
     return null; 
    }.... 

但是送我的請求時,我得到一個NullPointerException:

的Java。 lang.NullPointerException COM ... ResourceManager.validateResourceId(ResourceManager.java:861) COM ... management.resource.manager.ResourceManager.addResource(ResourceManager.java:127)

似乎工廠不能識別相關對象並返回null! 春天應該如何識別它應該映射json的對象?!還是我在做別的事情呢?

+0

發現一些有趣的東西,會給它一個嘗試:https://stackoverflow.com/questions/27170298/spring-reponsebody-requestbody-with-abstract-class – zbeedatm

回答

0

我試圖使用這些註釋: https://fasterxml.github.io/jackson-annotations/javadoc/2.4/com/fasterxml/jackson/annotation/JsonTypeInfo.html

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, 
      include = JsonTypeInfo.As.PROPERTY, 
      property = "resourcetype", 
      visible=true) 
@JsonSubTypes({ 
@JsonSubTypes.Type(value = DbServerResource.class, name = "dbServerResource"), 
@JsonSubTypes.Type(value = DbFileResource.class, name = "dbFileResource"), 
@JsonSubTypes.Type(value = FileResource.class, name = "fileResource") 
}) 

public abstract class DisplayResource{ 
protected String resourceName; 
@JsonProperty(value = "resourceType") protected Types resourceType; 

public enum Types { DB_SERVER, DB_FILE, FILE } 

但現在當我送我的POST請求我越來越狀態400錯誤的請求!

我的遙控器側現在看來是這樣的:

@RequestMapping (method = RequestMethod.POST, value="/resource") 
private @ResponseBody <T extends DisplayResource>T addResource(@RequestBody T resource) 
     throws ResourceManagementException, ConfigurationException, MalformedURLException{ 

    logger.info("Adding a new resource: " + resource.toString()); 

    ...  
    resourceManagerService.addResource("admin", resourceFactory.getResourceId(resource), credentials); 

    return resource; 
} 

GET方法仍正常工作。

相關問題