Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 对象到xml的映射格式化为Springbean定义_Java_Spring_Xml Serialization - Fatal编程技术网

Java 对象到xml的映射格式化为Springbean定义

Java 对象到xml的映射格式化为Springbean定义,java,spring,xml-serialization,Java,Spring,Xml Serialization,我正在寻找一种将java对象序列化为与Springbean定义相同格式的XML的方法。例如,类定义为: package x.y.z; class foo { String name; int counter; ...setter and getter omitted for simplicity .... } 类foo的对象将序列化为: <bean id="" class="x.y.z.foo"> <property name="name" v

我正在寻找一种将java对象序列化为与Springbean定义相同格式的XML的方法。例如,类定义为:

package x.y.z;
class foo {
    String name;
    int counter;

    ...setter and getter omitted for simplicity ....
}
类foo的对象将序列化为:

<bean id="" class="x.y.z.foo">
   <property name="name" value="some random value"/>
   <property name="counter" value="1" />
</bean>


其目的是,稍后我可以通过将xml复制/粘贴到spring上下文文件,将对象注入单元测试。

如果您对注释没有意见,类似于简单xml序列化的方法可以实现您所需要的功能。我也喜欢XStream,但它可能不适合于与类结构不同的XML

实际上,您最好只编写一个marshal(),甚至是一个带字符串缓冲区的脏封送:

public Element marshal() {
    StringBuffer sb = new StringBuffer();
    sb.append("\t<bean id="">\n");
        sb.append("\t\t<property name=\"").append(name).append(""/>\n");
    sb.append("\t</bean>\n");
    InputStream istream = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
    Document myDoc = new SAXBuilder().build(istream);
}
我认为,如果您的模式非常简单,但与XML不同,那么您可能会花更多的时间尝试配置XML序列化程序,而不是仅仅破解一个

    // Save it to a file:
    XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
    java.io.FileWriter writer = new java.io.FileWriter(fileName);
    out.output(document, writer);
    writer.flush();
    writer.close();