Spring:加载前检查类路径资源是否存在

2024-06-28

我有一个代码,需要检查类路径资源是否存在并应用一些操作。

File file = ResourceUtils.getFile("classpath:my-file.json");
if (file.exists()) {
    // do one thing
} else {
    // do something else
}

Problem: ResourceUtils.getFile() throws FileNotFoundException如果资源不存在。同时,我不想在代码流中使用异常,并且我想检查资源是否存在。

问题:有没有办法使用 Spring 的 API 检查资源是否存在?

为什么我需要用Spring来完成这个:因为如果没有 spring,我需要自己选择一个正确的类加载器,这很不方便。我需要有一个不同的代码才能使其在单元测试中工作。


您可以使用资源加载器接口 https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/ResourceLoader.html为了加载使用获取资源() https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/ResourceLoader.html#getResource-java.lang.String-,然后使用资源.exists() https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/Resource.html#exists--检查文件是否存在。

@Autowired
ResourceLoader resourceLoader;  

Resource resource = resourceLoader.getResource("classpath:my-file.json");
if (resource.exists()) {
  // do one thing
} else {
  // do something else
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring:加载前检查类路径资源是否存在 的相关文章

随机推荐