Get directory path from Spring bean?

I have what seems like a simple problem. I have a Spring web application deployed to Tomcat. In the service class, I want to be able to write a new file to a directory called graphs under my application root:

/ /WEB-INF /graphs/ /css/ /javascript/ 

My service class is Spring bean, but I do not have direct access to the ServletContext through the HttpServlet mechanism. I also tried implementing ResourceLoaderAware, but still can't find the handle to what I need.

How to use Spring to get a directory descriptor in my application so that I can write a file? Thanks.

+4
source share
2 answers

If your bean is controlled by the spring webapp context, you can implement ServletContextAware , and spring will inject the ServletContext into your bean. Then you can query ServletContext for the real file system path for this resource, for example.

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

If your bean is not inside the webapp context, it gets pretty ugly, something like 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 it is executed by the request thread.

+6
source

@All

The problem with these answers is that they become obsolete or information about how to act differently was not obvious at the time. Like this old Atari computer that you can use (grin), things could change!

You can simply @Autowired ServletContext in a bean:

 @Service class public MyBean { @Autowired ServletContext servletContext=null; // Somewhere in the code ... String filePathToGraphsDir = servletContext.getRealPath("/graphs"); } 
+10
source

Source: https://habr.com/ru/post/1304822/


All Articles