Skip to content

Instantly share code, notes, and snippets.

@conclube
Last active April 13, 2021 10:51
Show Gist options
  • Save conclube/a01d187ab9127149a919daec6547757f to your computer and use it in GitHub Desktop.
Save conclube/a01d187ab9127149a919daec6547757f to your computer and use it in GitHub Desktop.
Dependency Injection
public class Data {
/* Arbitrary data in this class */
}
public class DataManager {
private final Map<Player,Data> objects = new IdentityHashMap<>();
public void add(Player player, Data data) {
this.objects.put(player, data);
}
public void remove(Player player) {
this.objects.remove(player);
}
}
public class EventListener implements Listener {
private final HowToDependencyInjection plugin;
public EventListener(HowToDependencyInjection plugin) {
this.plugin = plugin;
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
DataManager dataManager = this.plugin.getDataManager();
dataManager.add(event.getPlayer(), new Data());
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
DataManager dataManager = this.plugin.getDataManager();
dataManager.remove(event.getPlayer());
}
}
//This is our main/entrypoint class, in spigot it's almost always the class which extends JavaPlugin
public final class HowToDependencyInjection extends JavaPlugin {
private DataManager dataManager;
@Override
public void onEnable() {
this.dataManager = new DataManager();
super.getServer().getPluginManager().registerEvents(new EventListener(this), this);
}
public DataManager getDataManager() {
return this.dataManager;
}
}
@conclube
Copy link
Author

conclube commented Apr 13, 2021

Here we use our main class as a context object which handles the creation for our DataManager. It also provides a getter to expose it such that it can be accessed outside our main class.

Then in the EventListener we pass our main class instance through its constructor and then we cache it into a field such that our main class instance can be reached in other methods within EventListener easily. To access the DataManager instance we simply use the getDataManager() method in the desired event handling method. In this case onQuit and onJoin.

NOTE: The object creation of DataManager is done before the EventListener since EventListener is depending on DataManager (line 6 & 8). This is to avoid NullPointerException but it would still not happen in this case as the event handling methods would not be called directly nevertheless it is still worth paying attention to as your case may be different such that the order in which objects are created and when their methods are invoked may vary entirely.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment