Spring Boot访问静态资源缺少scr/main/resources

len*_*h87 56 java resources spring spring-boot spring-properties

我正在开发一个Spring Boot应用程序.我需要在启动时解析XML文件(countries.xml).问题是我不明白把它放到哪里以便我可以访问它.我的文件夹结构是

ProjectDirectory/src/main/java
ProjectDirectory/src/main/resources/countries.xml
Run Code Online (Sandbox Code Playgroud)

我的第一个想法是将它放在src/main/resources中,但是当我尝试创建File(countries.xml)时,我得到一个NPE,堆栈跟踪显示我的文件在ProjectDirectory中查找(所以src/main/resources /没有添加).我尝试创建File(resources/countries.xml),路径看起来像ProjectDirectory/resources/countries.xml(所以再没有添加src/main).

我尝试添加这个没有结果

@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    super.addResourceHandlers(registry);
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以手动添加src/main /,但我想了解为什么它不能正常工作.我也尝试过使用ResourceLoader的示例 - 同样没有结果.

任何人都可以建议问题是什么?

更新: 仅供将来参考 - 在构建项目后,我遇到了访问文件的问题,因此我将File更改为InputStream

InputStream is = new ClassPathResource("countries.xml").getInputStream();
Run Code Online (Sandbox Code Playgroud)

lub*_*nac 113

只需使用Spring类型ClassPathResource.

File file = new ClassPathResource("countries.xml").getFile();
Run Code Online (Sandbox Code Playgroud)

只要这个文件在classpath的某个地方,Spring就会找到它.这可以src/main/resources在开发和测试期间进行.在生产中,它可以是当前运行的目录.

  • [根据这个答案](/sf/answers/1811159381/)`resource.getFile()`期望文件在实际的文件系统上,并且此解决方案在JAR内部无法访问存储在`src/main/resources`下的资源.我已经确认了一个简单的Spring Boot应用程序. (22认同)
  • @smeeb 谢谢。使用 `InputStream inputStream = new ClassPathResource("countries.xml").getInputStream();` 对我有用 (3认同)

San*_*wat 8

要获取类路径中的文件:

Resource resource = new ClassPathResource("countries.xml");
File file = resource.getFile();
Run Code Online (Sandbox Code Playgroud)

要读取onStartup文件,请使用@PostConstruct:

@Configuration
public class ReadFileOnStartUp {

    @PostConstruct
    public void afterPropertiesSet() throws Exception {

        //Gets the XML file under src/main/resources folder
        Resource resource = new ClassPathResource("countries.xml");
        File file = resource.getFile();
        //Logic to read File.
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个在Spring Boot App启动时读取XML文件的小例子.


Sac*_*ngh 8

在使用Spring Boot应用程序时,resource.getFile()当我面临同样的问题时,很难在部署为JAR时使用类路径资源.使用Stream解析此扫描,它将找出放置在类路径中任何位置的所有资源.

以下是相同的代码片段 -

ClassPathResource classPathResource = new ClassPathResource("fileName");
InputStream inputStream = classPathResource.getInputStream();
content = IOUtils.toString(inputStream);
Run Code Online (Sandbox Code Playgroud)


Gal*_*ley 5

我使用 spring boot,所以我可以简单地使用:

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