如何从引用java项目访问静态资源(WEB-INF)文件夹中的文件?

我有一个Web应用程序,它包含一个配置xml文件,用于我的一个应用程序服务,它作为spring bean公开。 此外,我在同一工作区中有一个独立的Java应用程序(它从其pom.xml引用我的Web应用程序项目),它使用Spring TestContext框架运行测试,其中一个测试检查该XML文件的配置。

但是我从独立应用程序访问此xml文件时遇到问题:

在设置测试之前,在我之前的配置中,该文件是通过ServletContext访问的,位于WEB-INF /文件夹中。 但是,为了使它可以从测试项目访问,我必须将它移动到源/文件夹并使用getClassLoader()。getResourceAsStream()方法加载它而不是ServletContext。 但它使编辑文件变得麻烦,因为每次必须重新部署应用程序。

是否可以将文件保存在WEB-INF /文件夹中,但在测试运行期间从引用项目中加载它?

PS目前它是一个带有Tomcat服务器的STS项目。

绝对将文件保存在WEB-INF /文件夹下,如果它应该存在的位置。

对于从命令行执行的测试类。 您可以在您知道的类路径根目录中的文件(例如application.properties文件)上使用getClassLoader()。getResource()。 从那里你知道项目的结构以及在哪里找到WEB-INF /相对于属性文件。 由于它返回一个URL,您可以使用它来找出您正在寻找的XML文件的路径。

URL url = this.getClass().getClassLoader().getResource("application.properties"); System.out.println(url.getPath()); File file = new File(url.getFile()); System.out.println(file); // now use the Files' path to obtain references to your WEB-INF folder 

希望你觉得这很有用。 我不得不对你的测试类如何运行等做出假设。

看一下File Class ,它的getPath(),getAbsolutePath()和getParent()方法可能对你有用。

我最终使用Spring MockServletContext类并在测试运行之前将其直接注入我的服务bean,因为我的服务实现了ServletContextAware

 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/test-ctx.xml" } ) public class SomeServiceTest { @Autowired private MyServletContextAwareService myService; @Before public void before(){ //notice that I had to use relative path because the file is not available in the test project MockServletContext mockServletContext = new MockServletContext("file:..//src/main/webapp"); myService.setServletContext(mockServletContext); } 

如果我有几个使用Servlet Context的类,那么更好的解决方案是使用WebApplicationContext而不是默认的(当前由DelegatingSmartContextLoader提供),但是它需要实现自定义ContextLoader类并将其类名传递给@ContextConfiguration注释。

后来我想到的替代和稍微清晰的解决方案是重构服务并通过@Autowired注入ServletContext而不是弄乱ServletContextAware ,并提供相应类型的bean(实际上是一个MockServletContext实例)。

可能,将来,测试类的MockServletContext的直接支持将被添加到Spring中,参见SPR-5399和SPR-5243 。

更新为Spring 3.2在Spring 3.2中,servlet上下文的初始化变得像添加一个@WebAppConfiguration注释一样简单:

 @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration("file:..//src/main/webapp") @ContextConfiguration(locations = { "/test-ctx.xml" } ) public class SomeServiceTest { 

请参阅文章中的详细信息

在Maven项目中,我遇到了同样的问题。 我没有servletContext,无法访问WEB-INF目录中的静态文件。 我通过在pom.xml中添加条目来访问该目录,从而找到了解决方案。 它实际上包含了这个到类路径的路径。

PS:我使用的是Tomcat容器

     src/main/webapp/WEB-INF    

它是一个类路径资源,所以把它放在类路径上:$ webapp / WEB-INF / classes

在打包webapp时,Maven项目会将$ module / src / main / resources中的内容复制到此位置。 (前者是一个源路径,后者 – WEB-INF / classes – 总是按照规范由servlet容器放在类路径上。)