Part V. 数据访问-21. 使用O/X Mappers编组XML-21.3 使用Marshal
Spring的OXM可用于各种情况。 在下面的示例中,我们将使用它将Spring管理的应用程序的设置作为XML文件进行编组。 我们将使用一个简单的JavaBean来表示设置: public class Settings {
应用程序类使用此bean来存储其设置。 除了主要的方法之外,该类还有两种方法: 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(); } } <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> 该应用程序上下文使用 此示例应用程序生成以下 "1.0" encoding="UTF-8" xml version= <settings foo-enabled="false"/> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |