对于 Spring Boot REST 端点,似乎如果 JAXB 可用,只需传递 'application/xml' 的 'Accept' header 就足以从一个非常简单的端点接收输出,只要 @Xml ...注释存在于实体上。
@RequestMapping(value = "/thing/{id}")
ResponseEntity<Thing> getThing(
@PathVariable(value = "id") String id) {
Thing thing = thingService.get(id)
return new ResponseEntity<Thing>(thing, HttpStatus.OK);
}
但是,当调用 jmsTemplate.convertAndSend(destination, thing)
时,我必须明确地将消息转换器插入到 JMS 模板中,该模板中包含以下代码
JAXBContext context = JAXBContext.newInstance(object.getClass());
Marshaller marshaller = context.createMarshaller();
StringWriter writer = new StringWriter();
marshaller.marshal(object, writer);
TextMessage textMessage = session.createTextMessage(writer.toString());
return textMessage;
我目前正在使用带有注释的 JavaConfig 和这些消息依赖项:
compile("org.springframework:spring-jms")
compile('org.springframework.integration:spring-integration-jms')
compile("org.apache.activemq:activemq-broker")
还包括来自 Spring Boot starter 的这些,但不确定它们在这里是否重要。
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-hateoas')
我也在使用 Groovy 和 Spock。
似乎肯定有某种方法可以在没有代码的情况下默认完成此编码。有什么建议吗?
最佳答案
我最终明确插入了 Spring OXM 框架中的 Jaxb2Marshaller。我做的有点笨拙,因为我正在做 SpringBoot 和基于注释的配置,而且示例都是 XML。
@Autowired
JmsTemplate jmsTemplate
...
@Bean
MessageConverter messageConverter() {
MarshallingMessageConverter converter = new MarshallingMessageConverter()
converter.marshaller = marshaller()
converter.unmarshaller = marshaller()
// set this converter on the implicit Spring JMS template
jmsTemplate.messageConverter = converter
converter
}
@Bean
Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller()
marshaller.classesToBeBound = [My.class, MyOther.class]
marshaller
}
我很想做得更简单,但恐怕现在只能这样了。
关于java - 将 Spring Boot JMS 应用程序配置为默认使用 JAXB 编码的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36412852/