[英]How to access file in the static resources(WEB-INF) folder from the referencing java project?
我有一个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:../<my web project name>/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:../<my web project name>/src/main/webapp")
@ContextConfiguration(locations = { "/test-ctx.xml" } )
public class SomeServiceTest {
请参阅文章中的详细信息
在Maven项目中,我遇到了同样的问题。 我没有servletContext,也无法访问WEB-INF目录中的静态文件。 我通过在pom.xml中添加条目来访问该目录,从而找到了解决方案。 它实际上包含了这个到类路径的路径。
PS:我使用的是Tomcat容器
<project>
<build>
<resources>
<resource>
<directory>src/main/webapp/WEB-INF</directory>
</resource>
</resources>
</project>
它是一个类路径资源,所以把它放在类路径上:$ webapp / WEB-INF / classes
在打包webapp时,Maven项目会将$ module / src / main / resources中的内容复制到此位置。 (前者是一个源路径,后者 - WEB-INF / classes - 总是按照规范由servlet容器放在类路径上。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.