【问题标题】:FileSytemResources in Spring FrameworkSpring 框架中的文件系统资源
【发布时间】:2010-03-04 10:50:26
【问题描述】:

我正在尝试在我的 Spring MVC 项目中检索 xml 文件(包含 bean 定义)。 如果我在 WEB-INF 目录下有 xml 文件,那么我应该将什么路径放入我的 servlet 中的 FileSystemResource 来检索 xml?

i.e. BeanFactory factory = new XmlBeanFactory(new FileSystemResource("xml"));

谢谢

【问题讨论】:

    标签: spring-mvc spring


    【解决方案1】:

    你不应该使用FileSystemResource,你应该使用ServletContextResource

    new ServletContextResource(servletContext, "/myfile.xml");
    

    当然,假设您可以使用 servletContext。

    如果你真的想要使用FileSystemResource,那么你需要询问容器目录在哪里,并将其用作相对路径,例如

    String filePath = servletContext.getRealPath("/myfile.xml");
    new FileSystemResource(filePath);
    

    不过,让 Spring 为您完成工作会更容易。假设你有一个需要这个Resource 的bean。您可以将资源路径作为字符串注入,并让 Spring 将其转换为资源,例如

    public class MyBean {
    
       private Resource myResource;
    
       public void setMyResource(Resource myResource) {
          this.myResource = myResource;
       }
    }
    

    在你的 bean 文件中:

    <bean id="myBean" class="MyBean">
       <property name="myResource" value="/path/under/webapp/root/of/my/file.xml">
    </bean>
    

    Spring 会将资源路径转换为 ​​ServletContextResource 并将其传递给您的 bean。

    【讨论】:

    • 谢谢!。在我的 servlet 中,我有 HttpServletRequest 和 HttpServletResponse,所以我使用“request.getRealPath()”而不是 servletContext.getRealPath()。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    • 2021-10-20
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多