Part V. 数据访问-21. 使用O/X Mappers编组XML-21.3 使用Marshaller和Unmarshaller

Spring的OXM可用于各种情况。 在下面的示例中,我们将使用它将Spring管理的应用程序的设置作为XML文件进行编组。 我们将使用一个简单的JavaBean来表示设置:

public class Settings {

private boolean fooEnabled;

public boolean isFooEnabled() {
return fooEnabled;
}

void setFooEnabled(boolean fooEnabled) {
this.fooEnabled = fooEnabled;
}
}

应用程序类使用此bean来存储其设置。 除了主要的方法之外,该类还有两种方法saveSettings()将设置bean保存到名为settings.xml文件中,loadSettings()再次加载这些设置。 一个main()方法构造一个Spring应用程序上下文,并调用这两个方法

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClasspathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;

Application {

static final String FILE_NAME = "settings.xml";
private Settings settings = new Settings();
private Marshaller marshaller;
private Unmarshaller unmarshaller;

setMarshaller(Marshaller marshaller) {
this.marshaller = marshaller;
}

setUnmarshaller(Unmarshaller unmarshaller) {
this.unmarshaller = unmarshaller;
}

saveSettings() throws IOException {
FileOutputStream os = null;
try {
os = new FileOutputStream(FILE_NAME);
this.marshaller.marshal(settings,new StreamResult(os));
} finally {
if (os != null) {
os.close();
}
}
}

loadSettings() throws IOException {
FileInputStream is = try {
is = new FileInputStream(FILE_NAME);
this.settings = (Settings) this.unmarshaller.unmarshal(new StreamSource(is));
} if (is != null) {
is.close();
}
}
}

static main(String[] args) throws IOException {
ApplicationContext appContext =
new ClasspathXmlApplicationContext("applicationContext.xml");
Application application = (Application) appContext.getBean("application");
application.saveSettings();
application.loadSettings();
}
}

Application需要设置marshallerunmarshaller属性。 我们可以使用以下applicationContext.xml

<beans>
<bean id="application" class="Application">
<property name="marshaller" ref="castorMarshaller" />
<property name="unmarshaller" ref="castorMarshaller" />
</bean>
<bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller"/>
</beans>

该应用程序上下文使用Castor,但是我们可以使用本章后面描述的其他编组器实例。 请注意,认情况下,Castor不需要任何进一步的配置,因此bean定义相当简单。 还要注意的是,CastorMarshaller实现了MarshallerUnmarshaller,因此我们可以在应用程序的unmarshaller属性中引用castorMarshallerbean。

此示例应用程序生成以下settings.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<settings foo-enabled="false"/>

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念