加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 02:02:25 所属栏目:百科 来源:网络整理
导读:Spring的OXM可用于各种情况。 在下面的示例中,我们将使用它将Spring管理的应用程序的设置作为XML文件进行编组。 我们将使用一个简单的JavaBean来表示设置: public class Settings { private boolean fooEnabled; public boolean isFooEnabled () { return

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"/>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读