资源
io.jmix.core.Resources 接口是一个核心基础设施 API,用于从不同位置加载资源。
当应用程序代码或框架配置需要加载可从类路径或外部配置目录提供的文件时,可以使用该接口。
资源位置
Resources 根据以下规则搜索资源:
-
如果位置是 URL,则从该 URL 加载资源。
-
如果位置以
classpath:前缀开头,则从类路径加载资源。 -
如果位置不是 URL 且不以
classpath:开头,Jmix 首先使用提供的位置作为相对路径,在 jmix.core.conf-dir 应用程序属性指定的目录中查找文件。 -
如果在配置目录中未找到该文件,Jmix 会在类路径中搜索。
实践中,资源通常从外部配置目录或类路径加载。配置目录中的文件会覆盖具有相同位置的类路径资源。
加载资源
注入 Resources:
@Autowired
private Resources resources;
使用 getResourceAsStream() 获取资源的 InputStream。如果未找到资源,该方法返回 null。使用后请关闭流:
@Autowired
private Resources resources;
@Subscribe
public void onInit(final InitEvent event) {
try (InputStream stream = resources.getResourceAsStream(SRC_PATH)) {
if (stream == null) {
// resource not found
return;
}
// use the stream
} catch (IOException e) {
throw new RuntimeException(e);
}
}
使用 getResourceAsString() 将资源内容加载为 UTF-8 字符串。如果未找到资源,该方法返回 null:
String content = resources.getResourceAsString("com/company/demo/sample.txt");
获取 Spring Resource
由于 Resources 扩展了 Spring 的 ResourceLoader,当需要 org.springframework.core.io.Resource 对象时,也可以使用 getResource():
Resource resource = resources.getResource("classpath:com/company/demo/sample.txt");
本页是否有帮助?
感谢您的反馈