在Spring Web应用程序中从类路径加载(xml)文件

MaV*_*ldo 11 java spring classpath

我想从我的类路径中获取一个xml文件来解组它并将其用于测试目的.我的问题是将它作为InputStream.我写了这些行,但我总是得到一个null结果.

InputStream is = getClass().getResourceAsStream("WebContent/WEB-INF/classes/testing/"+ COMPLETE_DOCUMENT + ".xml");
Run Code Online (Sandbox Code Playgroud)

当然,你在方法参数中看到的路径是我文件中的路径.我尝试了几种组合:

WebContent/WEB-INF/classes/testing/
classpath:testing/
classpath*:testing/
Run Code Online (Sandbox Code Playgroud)

但我总是得到InputStream = null.

我甚至试图切换到

 ClassLoader.getResourceAsStream(...)
Run Code Online (Sandbox Code Playgroud)

但没有任何反应.我想资源的路径是错误的,但我无法弄清楚在哪里.从我的servlet.xml中,我使用类路径中的一些资源来配置PropertyPlaceholderConfigurer或Jaxb2Marshaller,只需使用语法

"classpath:folder/file.xsd"
Run Code Online (Sandbox Code Playgroud)

它完美无缺.我想要加载我的xml的文件夹是上面示例中的一个兄弟.我错过了什么?

编辑: 我尝试遵循Spring ClassPathResource帮助程序类方法,我得到一个奇怪的行为:正如我之前所说,我已经有一些资源从类路径加载启动时的一些spring bean.如果我在dardo建议的代码中使用这些资源的路径如下:

ClassPathResource cpr = new ClassPathResource("xmlschemas/lrinode.xsd");
InputStream is = cpr.getInputStream();
Run Code Online (Sandbox Code Playgroud)

我还是得到了FileNotFound Exception!当然"xmlschemas/lrinode.xsd"是我成功启动时加载的xsd.即使我从应用程序的根目录开始使用资源的完整路径,它也不起作用.

我开始认为我错过了一些微不足道的东西.

dar*_*rdo 20

Spring提供了一个名为ClassPathResource的辅助类

所以类似于:

ClassPathResource cpr = new ClassPathResource("folder/file.xsd");
InputStream is = cpr.getInputStream();
Run Code Online (Sandbox Code Playgroud)

应该工作,希望这有帮助!

链接到API Doc:http: //static.springsource.org/spring/docs/3.0.x/api/org/springframework/core/io/ClassPathResource.html

边注

此外,如果您将其用于测试目的,可能需要连接映射到xsd的bean.

可能想要查看JAXB marshaller

http://static.springsource.org/spring-ws/site/reference/html/oxm.html#oxm-jaxb2-xsd