Any class defined in a module descriptor will be created and autowired automatically by Spring, optionally injecting host components, imported components, and components defined in your plugin. However, there are several cases, such as Confluence Jobs, where your object cannot be created via Spring and therefore, you need to find another way to access a component.
This should only be tried as a last resort. Make sure you aren't just working around a poorly designed circular dependency or avoiding passing components to objects instantiated from components.
The solution is to create a component that is injected with everything you need that then exposes those beans as static methods. For example, you could define this component in your atlassian-plugin.xml
:
1 2<component key="staticAccessor" class="com.example.myplugin.StaticAccessor />
Then code StaticAccessor
as follows:
1 2public class StaticAccessor { private static SpaceManager spaceManager; private static PluginSettingsFactory pluginSettingsFactory; private static MyComponent myComponent; public StaticAccessor(SpaceManager spaceManager, PluginSettingsFactory pluginSettingsFactory, MyComponent myComponent) { StaticAccessor.spaceManager = spaceManager; StaticAccessor.pluginSettingsFactory = pluginSettingsFactory; StaticAccessor.myComponent = myComponent; } public static SpaceManager getSpaceManager() { return spaceManager; } public static PluginSettingsFactory getPluginSettingsFactory() { return pluginSettingsFactory; } public static MyComponent getMyComponent() { return myComponent; } }
In this example, SpaceManager is a Confluence host component, PluginSettingsFactory is an imported component from SAL, and MyComponent is a component defined in your plugin.
Finally, in your class that can't be injected, you can now easily access the components you need statically from StaticAccessor.
This technique contains several patterns that are generally very bad, but acceptable here:
Rate this page: