Resources

The io.jmix.core.Resources interface is a central infrastructure API for loading resources from different locations.

It is useful when application code or framework configuration needs to load files that can be supplied either from the classpath or from the external configuration directory.

Resource Locations

Resources searches for a resource according to the following rules:

  1. If the location is a URL, the resource is loaded from this URL.

  2. If the location starts with the classpath: prefix, the resource is loaded from the classpath.

  3. If the location is not a URL and does not start with classpath:, Jmix first searches for the file in the directory specified by the jmix.core.conf-dir application property, using the provided location as a relative path.

  4. If the file is not found in the configuration directory, Jmix searches for it in the classpath.

In practice, resources are usually loaded either from the external configuration directory or from the classpath. A file in the configuration directory overrides a classpath resource with the same location.

Loading Resources

Inject Resources:

@Autowired
private Resources resources;

Use getResourceAsStream() to get an InputStream for the resource. The method returns null if the resource is not found. Close the stream after use:

@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);
    }
}

Use getResourceAsString() to load the resource content as a UTF-8 string. The method returns null if the resource is not found:

String content = resources.getResourceAsString("com/company/demo/sample.txt");

Getting Spring Resource

Because Resources extends Spring’s ResourceLoader, you can also use getResource() when you need a org.springframework.core.io.Resource object:

Resource resource = resources.getResource("classpath:com/company/demo/sample.txt");