[FREE] Dependency Injection - Spigot tutorials beginner friendly! #3

Status
This thread has been locked.

Phaze

Plugin Developer
Banned
Feedback score
0
Posts
70
Reactions
10
Resources
0

Hello everyone! Today I would like to show you all how to properly use dependency injection in your projects.

Here is a video explaining this concept more in depth:


So lets say you have a class called "Main" and you have methods in that class. (Some very popular ones the getConfig method that it inherits from JavaPlugin, or in this case a custom one we have made called getInt)

Code:
import org.bukkit.plugin.java.JavaPlugin;

public class Main extends JavaPlugin {

    @Override
    public void onEnable() {
  
    }

    @Override
    public void onDisable() {
  
    }

    //Notice that this is our custom method here, which we want to access somewhere else besides the main class
    public int getInt() {
       return 1;
    }
}

And we have one other class where we want to retrieve methods from the main class, which will be named Events in this example

In our Events class, you are going to want to create a constructor by typing
Code:
private Main main;

public Events(Main main) {
this.main = main; //assign the variable an instance of our Main class so it is not null
}

So that we have a variable of our main class.
Code:
private Main main;

public Events(Main main) {
this.main = main; //assign the variable an instance of our Main class so it is not null
}

@EventHandler
public void onJoin(PlayerJoinEvent e) {
//Lets say this is where you want to get the config, you can do so here using

main.getConfig();

But you may also notice that we can use any other method in our main class such as the custom one we made before, main.getInt(), which will return 1.

Before you can export your plugin, you will have to create an instance of your events class inside your onEnable so everything goes as planned
Code:
@Override
public void onEnable() {
new Events(this);
}
Where "this" is referring to the main class, since this will be inside the main class, so you are in turn assigning "private Main main;" inside your events class your main class.

Using dependency injection is an alternative to using the static methods provided with Bukkit,
Code:
private Main main = Main.getPlugin(Main.class); //Wouldn't recommend doing this

One Step Further:
Lets say for example you have a method inside your Events class called getAmount() and it returns an int of 3. Since creating more instances of the class to use it would not be fesable, to use this method in another class besides the main class where you created the instance, you will want to assign the instance to a variable and create a getter for it.
Code:
private Events events;

@Override
public void onEnable() {
this.events = new Events(this);
}

public Events getEvents() {
return events;
}
So lets say you have a class named "Commands" and want to use the getAmount() method in Events, you can now use dependency injection on the class "Commands" and use
Code:
int amount = main.getEvents().getAmount();

Common Errors:
A common error is getting a NullPointerException where your variable of Main is inside your Events class. This is because you did not assign it properly.

Hello guys, I just released my second video on the spigot tutorial series! In today's video, I show you guys how to create custom commands and use events.



In the video, here is a written explanation of some of the things I cover:

All events must be in a class that
Code:
implements Listener
, however you should generally use multiple classes for multiple listeners, as a single class can get cluttered over time as your plugin expands

Here is an example,
Code:
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

public class PhazeListeners implements Listener {

    @EventHandler
    public void onJoin(PlayerJoinEvent e) {
        Player p = e.getPlayer();
 
        p.sendMessage("this is a string");
    }
}

And all commands must
Code:
implements CommandExecutor {[CODE] like this class
[code]import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

public class PhazeCommands implements CommandExecutor {

    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String str, String[] args) {
 
        if (!(sender instanceof Player)) {
            sender.sendMessage("You are not a player!");
            return true;
        }
 
        Player p = (Player) sender;
 
        if (cmd.getName().equalsIgnoreCase("phazecommand")) {
            p.sendMessage("you used a command from the phaze plugin");
            return true;
        }
 
        return true;
    }

}

Note that in java, the ! is to signify the opposite, so
Code:
!true
is false and
Code:
!false
is true.

Also note that you must always check if the sender is an instance of a player BEFORE casting the player to the sender, this is a very common mistake that many people make.

I also want to point out that in todays video I used
Code:
cmd.getName()
, but you may also use
Code:
cmd.getLablel()
as it is probably the better option.

Since the command method says "public boolean" has boolean in the method name, it means it must either return true or false. In spigot, when the commands return false, they send the command usage to the player, which we generally do not want, you usually want to return true.

Now to register your listeners, you want two methods in your onEnable(),
Code:
        getCommand("phazecommand").setExecutor(new PhazeCommands());
        Bukkit.getPluginManager().registerEvents(new PhazeListeners(), this);

by typing
Code:
new PhazeListeners()
and
Code:
new PhazeCommands()
we are creating new instances of these classes. You must always register commands and events in your plugin before you can use them in game.

Your plugin.yml you can just copy from here,
Code:
main: me.phaze.phazetest.PhazeTest
author: Phaze
version: 1.0
name: Phaze
commands:
  phazecommand:
    description: PhazeCommand
    usage: /phazecommand

As the plugin.yml is space sensitive, messing up the spaces will cause errors.


Vocabulary in todays video:

String: A message in java that is surrounded by double quotes, " ".


-------------------------------------------------------------------------------------------------------

I appreciate any form of feedback, if you find something I said wrong in the video or made a mistake on, please just comment down below and I will be sure to fix it in the reserved slot


Hello, my name is Phaze, and I would like to present to you my new youtube series on spigot plugin development "QUICK TUTORIALS"

These tutorials are unlike any other, because in each quick tutorial you will learn something new in MINUTES and I will provide support to everyone.

 
Last edited:
PebbleHost
High performance, consistent uptime and fast support. Minecraft hosting that just works.

Phaze

Plugin Developer
Banned
Feedback score
0
Posts
70
Reactions
10
Resources
0
Reserved
 
Banned forever. Reason: Scamming (https://builtbybit.com/threads/phaze-scam-report.509219/)

ZP4RKER

Feedback score
17
Posts
227
Reactions
79
Resources
0
yeah... the title is a bit misleading but not only with the time. you also say its for absolute beginners, which means they wouldnt know what Java or Eclipse is, and you didnt really give much of an introduction so like... absolute beginners would be pretty confused.

not trying to discourage you at all, but maybe put a little more planning and effort into this and im sure you could make a much better tutorial :)
 

Phaze

Plugin Developer
Banned
Feedback score
0
Posts
70
Reactions
10
Resources
0
yeah... the title is a bit misleading but not only with the time. you also say its for absolute beginners, which means they wouldnt know what Java or Eclipse is, and you didnt really give much of an introduction so like... absolute beginners would be pretty confused.

not trying to discourage you at all, but maybe put a little more planning and effort into this and im sure you could make a much better tutorial :)
Hello, thanks for the feedback. This tutorial I wanted to go over the setup, I see what you mean by not knowing what eclipse or java is, but there are already thousands of tutorials on how to download eclipse. Mabye if I posted this in the description or made another video on how to download eclipse?
 
Banned forever. Reason: Scamming (https://builtbybit.com/threads/phaze-scam-report.509219/)

ZP4RKER

Feedback score
17
Posts
227
Reactions
79
Resources
0
Hello, thanks for the feedback. This tutorial I wanted to go over the setup, I see what you mean by not knowing what eclipse or java is, but there are already thousands of tutorials on how to download eclipse. Mabye if I posted this in the description or made another video on how to download eclipse?
There's absolutely nothing wrong with mentioning/linking another series which goes over Java and the basics of setting up Eclipse/any other IDE. Also, you didn't really explain why you used 1.8.8 (obviously a preference and nothing wrong with that) but you should have explained that you can use whichever version you wish.

Also a tip directly to you, if you haven't already learnt Maven or Gradle I would highly recommend doing so. It will save you the hassle and time of having to download the server jar then add it as a library/dependency. It also helps with SO MUCH more, it will honestly just make your life a lot easier. All IDEs have decent support for both Maven and Gradle in-built/pre-installed so its no hassle to get it set up either.

Anyways, I wish you luck with your series. I hope you enjoy making it, and others out there find it beneficial. If you ever need any help with something, feel free to message me and I'll be sure to give you a helping hand if I can.
 
Status
This thread has been locked.
Top