我在客户端和服务器上设置了使用Jaxb2的MarshallingMessageConverter
关注this问题。
这是在服务器端:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(marshallingMessageConverter());
}
public MarshallingHttpMessageConverter marshallingMessageConverter() {
return new MarshallingHttpMessageConverter(jaxb2Marshaller(), jaxb2Marshaller());
}
public Jaxb2Marshaller jaxb2Marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(new Class[]{
User.class
});
return marshaller;
}
}
客户端:
@Configuration
public class RESTConfig {
@Bean
public MarshallingHttpMessageConverter marshallingMessageConverter() {
return new MarshallingHttpMessageConverter(jaxb2Marshaller(), jaxb2Marshaller());
}
@Bean
public Jaxb2Marshaller jaxb2Marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(new Class[] {
User.class
});
return marshaller;
}
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
//converters.addAll(restTemplate.getMessageConverters());
converters.add(marshallingMessageConverter());
restTemplate.setMessageConverters(converters);
return restTemplate;
}
}
检查两个日志:
org.springframework.oxm.jaxb.Jaxb2Marshaller createJaxbContextFromClasses
INFO: Creating JAXBContext with classes to be bound [class com.cloudlb.model.User]
当我尝试检索用户时。我得到了这个
org.springframework.web.client.RestClientException:
Could not extract response: no suitable HttpMessageConverter found for response type [com.cloudlb.model.User] and content type [application/xml]
我错过了什么吗?
我检查它将其检索为String.class并且它工作正常。以XML文件格式返回。
我想实现XML&lt; - HTTP - &gt; XML&lt; - &gt;对象&gt;
User user = restTemplate.getForObject(url, User.class);
编辑:这是我的控制器
@Controller
@RequestMapping("/user")
public class UserServiceController {
@Autowired
private UserService userService;
public UserServiceController() {}
@RequestMapping(value="/{id}", method = RequestMethod.GET)
@ResponseBody
public User findUserById(@PathVariable("id") String id) {
return userService.findById(id);
}
}
提前谢谢。
答案 0 :(得分:1)
当我配置它时,我按如下方式定义了ContentNegotiatingViewResolver:
@Bean
public ContentNegotiatingViewResolver contentNegotiatingViewResolver() {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
Map<String, String> mediaTypes = new HashMap<String, String>();
mediaTypes.put("xml", "application/xml");
resolver.setMediaTypes(mediaTypes);
List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>();
viewResolvers.add(new BeanNameViewResolver());
resolver.setViewResolvers(viewResolvers);
return resolver;
}
然后从我的Controller我回来了:
return new ModelAndView("spotView", "spot", spot);
然后在我的配置中我定义了一个与控制器返回的视图同名的bean(因为我使用的是BeanName解析器):
@Bean
public MarshallingView spotView() {
return new MarshallingView(jaxbMarshaller());
}