Get path to directory from Spring bean?

12,958

Solution 1

If your bean is managed by the webapp's spring context, then you can implement ServletContextAware, and Spring will inject the ServletContext into your bean. You can then ask the ServletContext for the real, filesystem path of a given resource, e.g.

String filePathToGraphsDir = servletContext.getRealPath("/graphs");

If your bean is not inside a webapp context, then it gets rather ugly, something like may work:

ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
String pathToGraphsDir = requestAttributes.getRequest().getRealPath("/graphs");

This uses the deprecated ServletRequest.getRealPath method, but it should still work, although RequestContextHolder only works if executed by the request thread.

Solution 2

@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!

You can simply @Autowired the ServletContext into your bean:

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

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

}
Share:
12,958
D.C.
Author by

D.C.

Updated on June 04, 2022

Comments

  • D.C.
    D.C. almost 2 years

    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:

    /
       /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.

    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.

  • D.C.
    D.C. about 14 years
    Hi, and thanks for the answer. I'm curious about where you say "If your bean is managed by the webapp's spring context", when would a bean not be managed by the spring context? Do you mean that this wouldn't work if i tried to use the class in an application that wasn't a servlet web application? that would make sense, just clarifying.
  • skaffman
    skaffman about 14 years
    @Darren: Correct. Spring contexts don't have to be part of a webapp, they can exist standalone.
  • andronikus
    andronikus about 12 years
    Great! This worked perfectly for me. Could this be a new feature of Spring 3? If so it won't work with Spring 2.