2012-08-07 55 views
1

我想從我的DAO中的遠程位置讀取xml文件。向spring bean注入xml文件

<bean id="queryDAO" 
     class="com.contextweb.openapi.commons.dao.reporting.impl.QueryDAOImpl"> 
    <property name="dataSource" ref="myDS"/> 
    <property name="inputSource" ref="xmlInputSource"/> 
</bean> 

<bean id="fileInputStream" class="java.io.FileInputStream"> 
    <constructor-arg index="0" type="java.lang.String" 
        value="${queriesFileLocation}"/> 
</bean> 
<bean id="xmlInputSource" class="org.xml.sax.InputSource"> 
    <constructor-arg index="0" > 
    <ref bean="fileInputStream"/> 
    </constructor-arg> 
</bean> 

我能夠第一次讀取XML。對於後續請求,inputstream已耗盡。

回答

1

您正在使用FileInputStream這就是問題所在。一旦讀取了流中的數據,就無法再次讀取內容。小河已經到了盡頭。

解決此問題的方法是使用另一個類BufferedInputStream,它支持將流指向文件中任何位置的重置。

以下示例顯示BufferedInputStream僅打開一次,可用於多次讀取文件。

BufferedInputStream bis = new BufferedInputStream (new FileInputStream("test.txt")); 

     int content; 
     int i = 0; 

     while (i < 5) { 

      //Mark so that you could reset the stream to be beginning of file again when you want to read it. 
      bis.mark(0); 

      while((content = bis.read()) != -1){ 

       //read the file contents. 
       System.out.print((char) content); 
      } 
       System.out.println("Resetting "); 
       bis.reset(); 
       i++; 

     } 

    } 

有趕上。由於您不是自己使用此類,而是依賴於org.xml.sax.InputSource來執行此操作,因此您需要創建自己的InputSource,方法是擴展此類並覆蓋getCharacterStream()getByteStream()方法,以mark()reset()reset()爲文件的起始流。

2

希望你知道在春天,默認情況下所有的bean對象都是單例。所以嘗試通過在這些bean聲明中設置singleton="false"字段來提供fileInputStream和xmlInputSource作爲非單例。

+0

但我只想加載一次xml。可能嗎? – 2012-08-07 07:57:17

0

也許你可以嘗試內聯FileInputStream,所以它每次強制一個新的實例?

<bean id="queryDAO" class="com.contextweb.openapi.commons.dao.reporting.impl.QueryDAOImpl"> 
    <property name="dataSource" ref="contextAdRptDS"/> 
    <property name="inputSource"> 
     <bean class="org.xml.sax.InputSource"> 
      <constructor-arg index="0" > 
        <bean class="java.io.FileInputStream"> 
         <constructor-arg index="0" type="java.lang.String" value="${queriesFileLocation}"/> 
        </bean> 
      </constructor-arg> 
     </bean> 
    </property> 
</bean>