-
Notifications
You must be signed in to change notification settings - Fork 25
Using the sender scope
Spring has two built in scopes by default: singleton
and prototype
. However, this starter implements a third and more useful for spigot plugins: the sender
scope.
The sender
scope isolates all beans from each sender (console sender and players), this means that you can create services and components that will be completely unique for each player. This option of isolation allows you to develop without having to care about references of the Player
, such as initializing and cleaning.
Let's see a example, a simple command who creates a counter for each player and increments it.
With the normal scope:
@Component
@CommandLine.Command(name = "increment")
public class TestCommand implements Runnable, Listener {
@Autowired
private Context context;
private Map<CommandSender, Integer> counters = new HashMap<>();
@Override
public String run() {
CommandSender sender = context.getSender();
// increments the existing reference or creates a new one with the value 1
Integer newValue = counters.merge(sender, 1, (c) -> c + 1);
sender.sendMessage(String.valueOf(newValue));
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
counters.remove(event.getPlayer());
}
}
As you can see, there is a lot of boilerplate code for keeping the counter reference for each player, as well as manually cleaning after the quit event.
Let's look how it works on sender
scope:
@Component
@SenderScoped
@CommandLine.Command(name = "increment")
public class TestCommand implements Runnable {
@Autowired
private Context context;
private Integer counter = 0;
@Override
public String run() {
CommandSender sender = context.getSender();
sender.sendMessage(String.valueOf(counter++));
}
}
The sender scope is the only thing you need to declare before using this powerful bean isolation. You also don't need to care about cleaning those beans, it just works!
- Getting started
- Commands
- Utilities
- Context
- RxJava support
- Known issues
- Testing