XStream JavaBeanConverter Spring配置使用getter进行序列化

时间:2013-05-15 21:19:40

标签: spring java-ee xstream spring-oxm

我想在Spring配置中注册XStream JavaBeanConverter。我看到JavaBeanConverter注册的测试示例,如下所示。

    xstream.registerConverter(new JavaBeanConverter(xstream.getClassMapper(), "class"), -20); 

但是如何在我的spring配置中进行设置。

目前我的春季配置设置如下

 <bean
       class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
       <property name="order" value="1" />
       <property name="mediaTypes">
              <map>
                    <entry key="json" value="application/json" />
                    <entry key="xml" value="application/xml" />
              </map>
       </property>
       <property name="defaultViews">
              <list>
                    <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" >
                            <property name="renderedAttributes" value="document" />
                    </bean>
                    <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                           <property name="marshaller">
                                  <bean class="org.springframework.oxm.xstream.XStreamMarshaller" p:autodetectAnnotations="true">
                                     <property name="encoding" value="UTF-8" />
                                  </bean>
                            </property>
                            <property name="contentType" value="application/xml;charset=UTF-8" />
                            <property name="modelKey" value="person" />
                    </bean>                                                
              </list>
       </property>
       <property name="ignoreAcceptHeader" value="true" />

</bean>            

我正在为Alias和Converter使用xstream注释。

我尝试从JavaBeanConverter扩展自定义转换器。它很好地序列化了正常的属性,但是我希望它能序列化getXXX方法。

public class MyCustomConverter extends JavaBeanConverter  {

    public MyCustomConverter(Mapper mapper) {
        super(mapper);
    }
    @Override... marshal.. unmarshal... canConvert methods...
 }

非常感谢!

1 个答案:

答案 0 :(得分:0)

将其添加到marshaller bean定义中:

    <property name="converters">
      <util:list>
        <bean class="com.MyBeanConverter">
          <constructor-arg value="com.MyBean" index="0" />
        </bean>
      </util:list>
    </property>

然后,定义以下将实现转换的类

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.javabean.JavaBeanConverter;

public class MyBeanConverter extends JavaBeanConverter {

   public MyBeanConverter(Class<?> theClass) {  
 super(new XStream().getMapper(), theClass); 
   }

}