What is the best way to load a class or resource from a plugin?

 What is the best way to load a resource from the classpath?

Because of the different ways that application servers deal with class-loading, just calling this.getClass().getResourceAsStream() might not work the same everywhere Confluence is deployed. To help, we have a utility method that checks the various classloaders in a predictable order:

InputStream in = com.atlassian.core.util.ClassLoaderUtils.getResourceAsStream(filename, this)

Inside Plugins

Because plugins may be dynamically loaded, each plugin may have its own classloader, separate from the main Confluence application. This makes loading resources like properties files from inside a plugin JAR a little tricky.

If the class from which you are loading the resource is in the same jar as the resource file itself (i.e. it's all part of the same plugin), you can use ClassLoaderUtils as above, and everything will work fine.

However, if you are trying to load the file from a different plugin, or from the main application code, you'll need an instance of the pluginManager from spring:

InputStream in = pluginManager.getDynamicResourceAsStream(filename)

(That said, you must now ask yourself why you're loading an arbitrary resource from some other plugin? It seems like a really bad idea to me. If the plugin wants to export that resource to the rest of the application, it should provide some way of getting at it itself.)

Was this page helpful?

Have a question about this article?

See questions about this article

Powered by Confluence and Scroll Viewport