Spring MVC:从src/main/resources读取文件

man*_*ish 40 spring-mvc

我有一个maven Spring项目,里面有xml文件src/main/resources/xyz.xml.如何在spring MVC控制器中读取它.

我在用

InputStream is = getClass().getResourceAsStream("classpath:xyz.xml");
Run Code Online (Sandbox Code Playgroud)

isnull.

Nim*_*sky 80

Resource resource = new ClassPathResource(fileLocationInClasspath);
InputStream resourceInputStream = resource.getInputStream();
Run Code Online (Sandbox Code Playgroud)

使用ClassPathResource和接口资源.但是请确保正确地复制资源目录(使用maven),并且不会丢失它,例如,如果将测试作为测试上下文的一部分运行.

  • 在这种情况下,fileLocationInClasspath不应以"classpath:"开头. (2认同)

小智 25

对于基于spring的应用程序,您可以利用ResourceUtils类.

File file = ResourceUtils.getFile("classpath:xyz.xml")
Run Code Online (Sandbox Code Playgroud)

  • https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/ResourceUtils.html (2认同)
  • 该文档指出它“主要供框架内部使用”。 (2认同)

Rob*_*ond 14

这是加载类路径资源的一种方法.

Resource resource = applicationContext.getResource("classpath:xyz.xml");
InputStream is = resource.getInputStream();
Run Code Online (Sandbox Code Playgroud)


k13*_*13i 11

您可以@Value向bean 添加带注释的字段:

@Value("classpath:xyz.xml")
private Resource resource;
Run Code Online (Sandbox Code Playgroud)

然后简单地说:

resource.getInputStream();
Run Code Online (Sandbox Code Playgroud)