Skip to content

Dependency Injection

Christopher Nethercott edited this page Feb 25, 2022 · 9 revisions

Default Dependencies

The following are automatically injected for your convenience.

BungeeCord

@Dependency
private Plugin genericPlugin;

@Dependency
private MyPlugin myPlugin; // allows access to your plugin class

@Dependency
private PluginDescription pluginDescription;

Bukkit / Spigot / Paper etc

@Dependency
private JavaPlugin genericPlugin; // generic java plugin

@Dependency
private Plugin myPlugin; // your specific plugin & associated methods

@Dependency
private PluginManager pluginManager;

@Dependency
private Server server;

@Dependency
private BukkitScheduler bukkitScheduler;

@Dependency
private ScoreboardManager scoreboardManager;

@Dependency
private ItemFactory itemFactory;

@Dependency
private PluginDescriptionFile description;

Introduction

#86 added the ability to use a simple dependency injection mechanism. This allows developers who don't need a big framework like guice to use "dependencies" (singleton objects like your plugin instance or some UserHandler) in your command classes.

This page aims to give a short introduction into this feature.

Defining Dependencies

You define dependencies using your command manager.

It exposes two methods:

  • registerDependency(Class<? extends T> clazz, T instance)
  • registerDependency(Class<? extends T> clazz, String key, T instance)

Every dependency needs to have a key that is unique for the given class, if no key is given, the class's name is used as a key. By using keys, you can have multiple dependencies of the same class:

commandManager.registerDependency(File.class, "ConfigFolder", new File(getDataFolder(), "config"));
commandManager.registerDependency(File.class, "WorldsFolder", new File(getDataFolder(), "worlds"));

A more traditional usecase would be providing some simple handler to all your command classes

UserHandler userHandler = new UserHandler();
commandManager.registerDependency(UserHandler.class, userHandler);

If you try to register a class twice with the same key, including the default key, you will get an exception, but this will be supported in #93 to auto update dependencies

Using Dependencies

WIP!

To use the dependencies you defined above in your command classes, all you need to do is create a field of the class you registered and mark it with @Dependency.

@Dependency
private UserHandler userHandler;

ACF will then take care of making sure the correct value is injected into that field when you register the command class.

To use dependencies by key, all you need to do is to pass the key as the value for that annotation:

@Dependency("ConfigFolder")
private File configFolder;
@Dependency("WorldsFolder")
private File worldsFolder;

If you use no key, the class name will be used as a key. If no class with that key was registered, it will throw an error on injection.