我正在尝试从我的控制器返回一个对象,该对象应该由spring解析为xml。 但我在我的类中使用@XmlNamedObjectGraph(来自moxy eclipselink)注释来自定义返回的对象。所以我必须从marshaller设置属性MarshallerProperties.OBJECT_GRAPH。
如何在我的控制器中访问spring用来解析我的对象的marshaller?
即:
@RequestMapping(value = "/xml/", method = RequestMethod.GET, produces = "application/xml")
@ResponseBody
public ResponseEntity<Customer> getXml() {
Customer customer = _customerService.getById(12);
...
marshaller.setProperty(MarshallerProperties.OBJECT_GRAPH, "default");
...
return new ResponseEntity<>(customer, HttpStatus.OK);
}
提前感谢您的帮助。
答案 0 :(得分:2)
您需要实施自己的AbstractJaxb2HttpMessageConverter
类并覆盖其createMarshaller
方法,以便为Marshaller
提供您自己的属性。请查看Jaxb2RootElementHttpMessageConverter
以获取实施提示。
一旦实现了这样的类,就需要将它注册为带有MVC堆栈的HttpMessageConverter
。如果您是通过Java进行配置,请查看WebMvcConfigurationSupport#configureMessageConverters(..)
。如果您是通过XML完成的,请查看
<mvc:annotation-driven>
<mvc:message-converters>
<!-- bean goes here -->
</mvc:message-converters>
</mvc:annotation-driven>
答案 1 :(得分:2)
就像Sotirios Delimanolis说的那样。您必须实现自己的AbstractJaxb2HttpMessageConverter
。但除此之外,您已实现WebBindingInitializer
并将其注册为:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class="com.example.CommonWebBindingInitializer" />
</property>
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
<bean class="org.springframework.http.converter.ResourceHttpMessageConverter" />
<bean class="com.example.Jaxb2RootElementHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
答案 2 :(得分:0)
如果需要自定义编组器,创建编组视图并使用所需的属性配置编组器,这是配置JAXB编组器的示例(请参阅此answer):
<!-- XML view using a JAXB marshaller -->
<bean id="jaxbView" class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.company.AClass</value>
</list>
</property>
</bean>
</constructor-arg>
</bean>
<!-- Resolve views based on string names -->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>