Using Marshaller and Unmarshaller
你可以在各种情况下使用 Spring 的 OXM。在下面的例子中,我们用它把一个 Spring 管理的应用程序的设置作为一个 XML 文件来管理。在下面的例子中,我们用一个简单的 JavaBean 来表示这些设置:
public class Settings {private boolean fooEnabled;public boolean isFooEnabled() {return fooEnabled;}public void setFooEnabled(boolean fooEnabled) {this.fooEnabled = fooEnabled;}}
应用程序类使用这个 Bean 来存储其设置。除了一个 main 方法,该类还有两个方法: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;public class Application {private static final String FILE_NAME = "settings.xml";private Settings settings = new Settings();private Marshaller marshaller;private Unmarshaller unmarshaller;public void setMarshaller(Marshaller marshaller) {this.marshaller = marshaller;}public void setUnmarshaller(Unmarshaller unmarshaller) {this.unmarshaller = unmarshaller;}public void saveSettings() throws IOException {try (FileOutputStream os = new FileOutputStream(FILE_NAME)) {this.marshaller.marshal(settings, new StreamResult(os));}}public void loadSettings() throws IOException {try (FileInputStream is = new FileInputStream(FILE_NAME)) {this.settings = (Settings) this.unmarshaller.unmarshal(new StreamSource(is));}}public static void main(String[] args) throws IOException {ApplicationContext appContext =new ClassPathXmlApplicationContext("applicationContext.xml");Application application = (Application) appContext.getBean("application");application.saveSettings();application.loadSettings();}}
这个应用环境使用了 XStream,但我们也可以使用本章后面描述的任何其他 marshaller实例。注意,在默认情况下,XStream 不需要任何进一步的配置,所以 Bean 的定义相当简单。还要注意的是,XStreamMarshaller 同时实现了 Marshaller 和 Unmarshaller,所以我们可以在应用程序的marshaller 和 unmarshaller 属性中都引用 xstreamMarshaller Bean。
:::tips
想要上面的程序可以运行,你需要在 spring ioc 环境下,添加这里用到的 oxm 和 xstream
implementation group: ‘org.springframework’, name: ‘spring-oxm’, version: ‘5.3.15’
// 其中 XStreamMarshaller 的实现又依赖了 xstream 包
implementation group: ‘com.thoughtworks.xstream’, name: ‘xstream’, version: ‘1.4.19’
:::
这个示例应用程序产生了以下 settings.xml 文件。
<?xml version="1.0" encoding="UTF-8"?><settings foo-enabled="false"/>
我测试的时候由于这些类都有完整的类目,生成的如下:
<cn.mrcode.study.springdocsread.data.Settings><fooEnabled>false</fooEnabled></cn.mrcode.study.springdocsread.data.Settings>
- 没有
<?xml version="1.0" encoding="UTF-8"?>声明 - 没有上图中那样的结构
