Marshaller和Unmarshaller用法

application_marshaller配置
<bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller"/>
<bean id="application" class="spring.mashaller.Application">
  <property name="marshaller" ref="castorMarshaller" />
  <property name="unmarshaller" ref="castorMarshaller" />
</bean>


Application.java配置
public class Application {
  private static final String FILE_NAME = "settings.xml";
  private Settings settings = new Settings();
  private Marshaller marshaller;
  private Unmarshaller unmarshaller;
  //marshaller和unmarshaller的setter方法忽略
  //saveSetting方法
  public void 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();
      }
    }
  }
  //loadSetting方法
  public void loadSettings() throws IOException {
    FileInputStream is = null;
    try {
      is = new FileInputStream(FILE_NAME);
      this.settings = (Settings) 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_mashaller.xml");
    Application application = (Application) appContext.getBean("application");
    application.saveSettings();
    application.loadSettings();
  }
}


Setting.java配置
public class Settings {
  private boolean fooEnabled;
  //getter和setter方法忽略
}

你可能感兴趣的:(marshal)