您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

我最终使用SpringMockServletContext类,并在测试运行之前将其直接注入到我的服务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类并将其类名传递给 批注。

是重构服务并ServletContext 通过@Autowired而不是进行注入ServletContextAware,并提供相应类型的bean(实际上是一个MockServletContext实例)。

将来可能 MockServletContext会在Spring中 添加来自测试类的直接 支持,请参阅 SPR-5399SPR-5243

在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 {

查看文章中的详细信息

java 2022/1/1 18:14:56 有488人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶