java 从 Spring bean 获取目录的路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2496544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get path to directory from Spring bean?
提问by D.C.
I have what seems like a simple problem. I have a Spring web app, deployed in Tomcat. In a service class I want to be able to write a new file to a directory called graphs just under my application root:
我有一个看起来很简单的问题。我有一个部署在 Tomcat 中的 Spring Web 应用程序。在服务类中,我希望能够将一个新文件写入我的应用程序根目录下名为 graphs 的目录:
/
/WEB-INF
/graphs/
/css/
/javascript/
My service class is a Spring bean, but I don't have direct access to ServletContext through the HttpServlet machinery. I've also tried implementing ResourceLoaderAware but still can't seem to grab a handle to what I need.
我的服务类是一个 Spring bean,但我不能通过 HttpServlet 机制直接访问 ServletContext。我也尝试过实现 ResourceLoaderAware 但似乎仍然无法掌握我需要的东西。
How do I use Spring to get a handle to a directory within my application so that I can write a file to it? Thanks.
如何使用 Spring 获取应用程序中目录的句柄,以便我可以向其中写入文件?谢谢。
回答by Frank C.
@All
@全部
The problem with these answers are they get stale or the information for doing things in multiple ways was not readily apparent at the time. Like that old Atari computer you may be using (grin), things may have changed!
这些答案的问题在于它们变得陈旧,或者以多种方式做事的信息在当时并不明显。就像您可能正在使用的旧 Atari 计算机一样(咧嘴笑),事情可能已经改变了!
You can simply @Autowiredthe ServletContext into your bean:
您可以简单地@Autowired将 ServletContext 放入您的 bean 中:
@Service
class public MyBean {
@Autowired ServletContext servletContext=null;
// Somewhere in the code
...
String filePathToGraphsDir = servletContext.getRealPath("/graphs");
}
回答by skaffman
If your bean is managed by the webapp's spring context, then you can implement ServletContextAware, and Spring will inject the ServletContextinto your bean. You can then ask the ServletContextfor the real, filesystem path of a given resource, e.g.
如果您的 bean 由 webapp 的 spring 上下文管理,那么您可以实现ServletContextAware,并且 Spring 会将 注入ServletContext到您的 bean 中。然后,您可以询问ServletContext给定资源的真实文件系统路径,例如
String filePathToGraphsDir = servletContext.getRealPath("/graphs");
If your bean is not inside a webapp context, then it gets rather ugly, something like may work:
如果您的 bean 不在 webapp 上下文中,那么它会变得相当丑陋,例如可能会起作用:
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
String pathToGraphsDir = requestAttributes.getRequest().getRealPath("/graphs");
This uses the deprecated ServletRequest.getRealPathmethod, but it should still work, although RequestContextHolderonly works if executed by the request thread.
这使用了不推荐使用的ServletRequest.getRealPath方法,但它应该仍然有效,尽管RequestContextHolder只有在由请求线程执行时才有效。

