簡體   English   中英

在春天加載xml文件

[英]Load xml file in spring

我想將xml文件加載到spring bean中以進行進一步處理。 我知道可以僅在spring配置文件中定義bean屬性來加載properties文件。 是否可以對xml文件執行相同操作?

編輯例如,我想要一個bean:

public class Bean {
   private File file
   public void setFile(File file) {
      this.file = file
   }
  //....
}

在我的配置文件中,我想要這樣設置:

<bean id="bean" class="blabla.Bean">
   <property name="file" value="smth here"/>
</bean>

然后我想使用DOM解析該xml

您可以通過將參數類型更改為Resource來實現它- 文檔中有更多詳細信息。 您可以從資源對象獲取文件句柄

public class Bean {
   private File file
   public void setFile(Resource resource) {
      this.file = resource.getFile()
   }
  //....
}

在配置文件中,您可以像這樣進行設置。 您可以使用類路徑:如果文件是類路徑中jar的一部分。 如果在外部,則需要使用該文件:

<bean id="bean" class="blabla.Bean">
   <property name="file" value="file:path to file"/>
</bean>

PropertyPlaceholderConfigurer已經通過DefaultPropertiesPersister支持xml屬性文件

屬性的xml文件格式如下。

   <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
    <properties>
        <entry key="key1">Value 1</entry>
        <entry key="key2">Value 2</entry>
    </properties>

您可以使用

  <context:property-placeholder 
  location="classpath:/com/myProject/spring_prop.xml" />
      <bean id="bean" class="org.MyBean">
         <property name="key1" value="${key1}" />
      </bean>

將您的配置文件更改為以下內容,

<bean id="bean" class="blabla.Bean">
   <property name="file" ref="file"/>
</bean>

<bean id="file" class="java.io.File">
   <constructor-arg type="string"><value>C:\myfile.xml</value></constructor-arg>
</bean>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM