2015-11-27 91 views
1

我會遇到一個問題,我無法弄清楚。Springboot json的模型沒有默認的構造函數

語境

我有一個控制器:

@RestController 
@RequestMapping("/classroom") 
public class ClassroomController { 

    @Inject 
    private ClassroomManager classroomManager; 

    @RequestMapping(value= "", method = RequestMethod.POST) 
    public Classroom create(Classroom classroom) { 
     ... some checks ... 
     return classroomManager.create(classroom); 
    } 
} 

模型類:

public class Classroom { 

    private Long id; 
    private final String name; 
    private final RoomCapacity roomCapacity; 
    private final Set<RoomEquipment> equipments = new HashSet<>(); 
    [... No setter, No default constructor ...] 



    public Classroom(String name, RoomCapacity roomCapacity) { 
     [... some checks ...] 
     this.name = name; 
     this.roomCapacity = roomCapacity; 
    } 
} 

問題是,我不能用作爲課堂JSON發送POST請求。

當我這樣做,我面對此異常:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.ubp.ent.backend.core.model.classroom.Classroom]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.ubp.ent.backend.core.model.classroom.Classroom.<init>() 

什麼是我的問題

我理解錯誤,我可能會添加一個默認的構造函數的類。
但點Classroom是從模型,我不想允許默認實例化。

我該如何讓Spring能夠從Json構建?

+0

你將需要添加一個服務豆的觀點來交換數據,如果你不想在實體 –

+0

我很抱歉,但什麼是服務bean默認的構造函數?我如何實現這個? –

+1

我不記得它是什麼,但我相信有一個傑克遜註釋可以應用於構造函數,告訴它使用該註釋來反序列化。 – chrylis

回答

1

您需要使用HttpMessageConverter,並以@RequestBody的形式接收參數。

@RequestMapping(value= "", method = RequestMethod.POST) 
public Classroom create(@RequestBodyClassroom classroom) { 
    ... some checks ... 
    return classroomManager.create(classroom); 
} 

public class ClassroomConverter extends AbstractHttpMessageConverter<Classroom> { 
... 
} 


@Configuration 
@EnableWebMvc 
@ComponentScan 
public class WebConfiguration extends WebMvcConfigurerAdapter { 

    @Override 
    public void configureMessageConverters(List<HttpMessageConverter<?>> httpMessageConverters) { 
     httpMessageConverters.add(new ClassroomConverter(new MediaType("text", "csv"))); 
    } 
} 

在這裏有與你相似

http://www.beabetterdeveloper.com/2013/07/spring-mvc-requestbody-and-responsebody.html

+0

謝謝,我會看看這個 –

相關問題