Spring MVC在没有请求的情况下获取WEB-INF下的文件

我想在/WEB-INF/.../下获取一个文件(或目录)

在请求之外。 我需要在服务器启动时加载的bean中。

我可以找到的所有解决方案都要使用ClassPathXmlApplicationContext的XML文件或获取servlet上下文或使用当前执行类的请求。 对我来说似乎很难看。

如何获取File("/WEB-INF/myDir/") 。 必须要有办法,不!?

只要您的bean在Web应用程序上下文中声明,您就可以获得ServletContext的实例(使用ServletContextAware或通过自动assembly)。

然后,您可以直接访问webapp目录中的文件( getResourceAsStream()getRealPath() ),或使用ServletContextResource

由momo编辑:

 @Autowired ServletContext servletContext; ... myMethod() { File rootDir = new File( servletContext.getRealPath("/WEB-INF/myDIR/") ); } 

我使用Spring DefaultResourceLoaderResource来读取WEB-INF或* .jar文件中的任何资源。 像魅力一样工作。 祝你好运!

 import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; public static void myFunction() throws IOException { final DefaultResourceLoader loader = new DefaultResourceLoader(); LOGGER.info(loader.getResource("classpath:META-INF/resources/img/copyright.png").exists()); Resource resource = loader.getResource("classpath:META-INF/resources/img/copyright.png"); BufferedImage watermarkImage = ImageIO.read(resource.getFile()); } 
 ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource("files/test.xml").getFile()); 

“files”文件夹应该是“main / resources”文件夹的子文件夹

如果文件位于WEB_INF\classes目录中,则可以使用classpath资源。 使用普通的maven构建将src/main/resources目录中的任何文件复制到哪个位置…

 import org.springframework.core.io.Resource ... final Resource yourfile = new ClassPathResource( "myfile.txt"); 

如果您只想从服务(而不是通过ServletContext)访问它,您可以这样做:

  final DefaultResourceLoader loader = new DefaultResourceLoader(); Resource resource = loader.getResource("classpath:templates/mail/sample.png"); File myFile = resource.getFile(); 

请注意,最后一行可能会抛出IOException因此您需要捕获/重新抛出

请注意,该文件位于: src\main\resources\templates\mail\sample.png

与你的问题没有完全相关,但是…这里有一些普遍的说法我曾经在Web应用程序中的任何地方加载属性,比如Spring做的(支持WEB-INF / …,类路径:…,文件:.. )。 是基于使用ServletContextResourcePatternResolver 。 您将需要ServletContext

 private static Properties loadPropsTheSpringWay(ServletContext ctx, String propsPath) throws IOException { PropertiesFactoryBean springProps = new PropertiesFactoryBean(); ResourcePatternResolver resolver = new ServletContextResourcePatternResolver(ctx); springProps.setLocation(resolver.getResource(propsPath)); springProps.afterPropertiesSet(); return springProps.getObject(); } 

我在自定义servlet上下文侦听器中使用了上面的方法,而conext尚未加载。