我最近在项目中添加了Spring-data,然后发现在我的REST控制器中,客户端提供的模型不再从JSON自动序列化。我该如何解决?
我添加了:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
现在User
参数没有调用它的String
arg构造函数,而u
为空!
@PostMapping()
@ResponseBody
public User createUser(HttpServletRequest request, @RequestParam("user") User u) {
log.info("Got user! " + u);
users.save(u);
Optional<User> found = users.findById(u.getEmail());
log.info("Saved user!! ");
return found.get();
}
答案 0 :(得分:0)
如果使用spring数据构建.war ,运行java -jar <path-to-war> --debug
,然后在不使用spring数据的情况下构建/运行它,并比较输出,您可以看到以下bean添加spring-data时会包含在内。
SpringDataWebAutoConfiguration matched:
- @ConditionalOnClass found required classes 'org.springframework.data.web.PageableHandlerMethodArgumentResolver', 'org.springframework.web.servlet.config.annotation.WebMvcConfigurer' (OnClassCondition)
- found ConfigurableWebEnvironment (OnWebApplicationCondition)
- @ConditionalOnMissingBean (types: org.springframework.data.web.PageableHandlerMethodArgumentResolver; SearchStrategy: all) did not find any beans (OnBeanCondition)
SpringDataWebAutoConfiguration#pageableCustomizer matched:
- @ConditionalOnMissingBean (types: org.springframework.data.web.config.PageableHandlerMethodArgumentResolverCustomizer; SearchStrategy: all) did not find any beans (OnBeanCondition)
SpringDataWebAutoConfiguration#sortCustomizer matched:
- @ConditionalOnMissingBean (types: org.springframework.data.web.config.SortHandlerMethodArgumentResolverCustomizer; SearchStrategy: all) did not find any beans (OnBeanCondition)
这是因为Spring数据公开了链接到您的数据存储库的REST控制器,如此处所述:http://spring.io/projects/spring-data-rest,这破坏了序列化传递给REST控制器的对象的默认自动配置。
只需排除自动配置,您现有的自动序列化将起作用:
@SpringBootApplication(exclude = { SpringDataWebAutoConfiguration.class })
public class MyApplication{
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}