2012-08-07 2 views
1

내 DAO의 원격 위치에서 xml 파일을 읽으려고합니다.스프링 콩에 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을 읽을 수 있습니다. 후속 요청의 경우, 입력 스트림이 고갈됩니다.

답변

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++; 

     } 

    } 

catch가 있습니다. 이 클래스는 직접 사용하지 않으므로 org.xml.sax.InputSource에 종속되므로이 클래스를 확장하고 getCharacterStream()getByteStream() 메서드를 mark()reset()으로 재정의하여 파일 시작 스트림을 직접 작성해야합니다.

2

봄에 기본적으로 모든 bean 객체는 싱글 톤이라는 것을 알고 계실 것입니다. 따라서 빈 선언에서 필드 singleton="false"을 설정하여 fileInputStream 및 xmlInputSource를 non-singleton으로 언급하십시오.

+0

하지만 xml을 한 번만로드하려고합니다. 가능한가? –

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>