体验 Spring 的 Object/XML 映射支持
2009-12-09 00:00:00 来源:WEB开发网另一个 bean 是 castorMarshaller bean 本身,它是 org.springframework.oxm.castor.CastorMarshaller 的一个实例,org.springframework.oxm.castor.CastorMarshaller 主要用于包装 Castor 框架。如前所述,使用 Spring 的 O/X 功能需要使用一个第三方 O/X 框架。在本例中,这个第三方产品是 Castor。还要注意,有一个属性使用 castorMarshaller 定义,那是用于在 Java bean 和 XML 输出之间来回映射的映射文件。这个文件称为 mapping.xml,它必须 在运行时位于类路径中。我将稍后解释 mapping.xml 文件的内容。
清单 2 实际执行 O/X 映射器的代码的部分清单。如您所见,它是一个简单的 Java 类。
清单 2. OXMExample 类(节选)
public class OXMExample {
private static final String FILE_NAME = "simplebean.xml";
private SimpleBean simpleBean;
private Marshaller marshaller;
private Unmarshaller unmarshaller;
public void setMarshaller(Marshaller marshaller) {
this.marshaller = marshaller;
}
public void setUnmarshaller(Unmarshaller unmarshaller) {
this.unmarshaller = unmarshaller;
}
public void saveSimpleBean() throws IOException {
FileOutputStream os = null;
try {
os = new FileOutputStream(FILE_NAME);
this.marshaller.marshal(simpleBean, new StreamResult(os));
} finally {
if (os != null) {
os.close();
}
}
}
public void loadSimpleBean() throws IOException {
FileInputStream is = null;
try {
is = new FileInputStream(FILE_NAME);
this.simpleBean
= (SimpleBean) this.unmarshaller.unmarshal(new StreamSource(is));
} finally {
if (is != null) {
is.close();
}
}
}
public static void main(String[] args) throws IOException {
ApplicationContext appContext
= new ClassPathXmlApplicationContext("applicationContext.xml");
OXMExample ex = (OXMExample) appContext.getBean("oxmExample");
ex.go();
}
private void go() throws IOException {
simpleBean = getSimpleBean();
saveSimpleBean();
loadSimpleBean();
System.out.println("name: " + simpleBean.getName());
System.out.println("job description: " + simpleBean.getJobDescription());
System.out.println("age: " + simpleBean.getAge());
System.out.println("executive: " + simpleBean.isExecutive());
}
private SimpleBean getSimpleBean() {
SimpleBean simpleBean = new SimpleBean();
simpleBean.setAge(35);
simpleBean.setExecutive(false);
simpleBean.setJobDescription("Janitor");
simpleBean.setName("Mister Jones");
return simpleBean;
}
}
更多精彩
赞助商链接