2013-09-23 104 views
0

让我描述像以下我的情况:我 创建我的春天MVC的web应用,结构是这样的:获取XML文件的工作路径

-Trainingapp 
    -Java Resources 
     -src/test/java 
     -src/test/resources 
     -src/main/java 
      -com.example.controller 
      -com.example.dao 
       -ReadAttributesService.java 
      -com.example.ctx 
       -AppContext.java 
      -com.example.pojos 
     -src/main/resources 
      -META-INF 
       -applicationContext.xml 
      settings.xml 

ReadAttributesService的构造函数需要一个文件路径参数从settings.xml中解析转换成XMLBeans。我希望应用程序创建ReadAttributesService的豆,所以我把这个给我applicationContext.xml文件

<!-- ReadAttributesService bean --> 
<bean id="readAttributesService" class="com.example.dao.ReadAttributesService"> 
    <constructor-arg name="filePath" value="src/main/resources/settings.xml" /> 
</bean> 

不管我给了ApplicationContext的文件路径的值行不通的,至少与我所确定完成。最后,我想创建一个新的FileInputStream的settings.xml,但我还没有找到任何方法来实现这一点。

所以,把这个简单,我想问我怎么能创建一个FileInputStream或类似我的spring-mvc webapplication中settings.xml的AbsolutePath? 先进的谢谢,任何帮助真的appriciate。

回答

0

如果你只需要一个InputStream(而不是一个FileInputStream),因为settings.xml应该在你的classpath中,我会尝试使用Spring Resources。你的XML bean声明应该是这个样子:

<!-- ReadAttributesService bean --> 
<bean id="readAttributesService" class="com.example.dao.ReadAttributesService"> 
    <constructor-arg name="settings" value="settings.xml" /> 
</bean> 

随着ReadAttributesService像构造ARG:

public class ReadAttributesService { 

    public ReadAttributesService(org.springframework.core.io.Resource settings){ 
     ... 
    } 
    ... 
} 

Spring会自动转换settings.xml串入Resource(这实际上是一个ClassPathResource) 。

从那里您应该可以调用该资源的getInputStream()方法。

如果你真的需要FileInputStream,它会变得棘手。

+0

不,资源和ClassPathResource足够了:D谢谢! – nhduc