从Spring bean获取目录的路径?

D.C*_*.C. 4 java resources spring

我有一个看似简单的问题.我有一个部署在Tomcat中的Spring Web应用程序.在服务类中,我希望能够在我的应用程序根目录下将一个新文件写入名为graphs的目录:

/
   /WEB-INF
   /graphs/
   /css/
   /javascript/
Run Code Online (Sandbox Code Playgroud)

我的服务类是一个Spring bean,但是我没有通过HttpServlet机器直接访问ServletContext.我也尝试过实现ResourceLoaderAware,但似乎仍无法抓住我需要的东西.

如何使用Spring来获取应用程序中目录的句柄,以便我可以将文件写入其中?谢谢.

Fra*_* C. 10

@所有

这些答案的问题是它们变得陈旧,或者当时以多种方式做事的信息并不明显.就像你可能正在使用的旧Atari电脑(笑)一样,事情可能已经改变了!

你可以简单地@Autowired将ServletContext放入你的bean中:

@Service
class public MyBean {
    @Autowired ServletContext servletContext=null;

    // Somewhere in the code
    ...
    String filePathToGraphsDir = servletContext.getRealPath("/graphs");

}
Run Code Online (Sandbox Code Playgroud)


ska*_*man 6

如果您的bean由webapp的spring上下文管理,那么您可以实现ServletContextAware,Spring将注入ServletContext您的bean.然后,您可以询问ServletContext给定资源的真实文件系统路径,例如

String filePathToGraphsDir = servletContext.getRealPath("/graphs");
Run Code Online (Sandbox Code Playgroud)

如果你的bean不在webapp上下文中,那么它会变得相当丑陋,类似可能会起作用:

ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
String pathToGraphsDir = requestAttributes.getRequest().getRealPath("/graphs");
Run Code Online (Sandbox Code Playgroud)

这使用了弃用的ServletRequest.getRealPath方法,但它仍然可以工作,尽管RequestContextHolder只有在请求线程执行时才有效.