Skip to content
LeeGod edited this page Dec 2, 2021 · 4 revisions

Component

Component is inherited from BaseContainerObject, it's a single instance ContainerObject that has a parent CompoentRegistry to handle construction. It's a very unique solution for things that may require registration. by using Component, you can save up a lot of times of these process, just have a registry and you can use Component to scan through, register, and handle life cycles for every classes.

To use Component, you need to have CompoentRegistry setup completed. And create a class where you want the Component to be, and put @io.fairyproject.container.Component on top of it, finally extend/implements the class that CompoentRegistry are listening too.

There are also some premade CompoentRegistry that are already usable directly. For example, Bukkit listeners, you may be familler to this pattern where you keep registering listener in main class whenever you have new listener class.

import org.bukkit.plugin.java.JavaPlugin;

public class ExamplePlugin extends JavaPlugin {

    @Override
    public void onEnable() {
        this.getServer().getPluginManager().registerEvents(new ExampleListener(), this);
    }
}

And whenever you created new listener, you need to copy and paste the line this.getServer().getPluginManager().registerEvents() to register the class.

With the use of Component, this is no longer the case, just put @Component on top of the Listener class and it's done! For example:

package io.fairyproject.examplePlugin;

import io.fairyproject.container.Component;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

@Component
public class ExampleListener implements Listener {

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        final Player player = event.getPlayer();
        player.sendMessage("Welcome!");
    }
    
}

Important note for Component

Component's CONSTRUCT and PRE_INIT state is deprioritized compare to Service's PRE_INIT, PRE_INIT of Service will always be first, and then CONSTRUCT & PRE_INIT Component

To expand Component into it full potential, I would suggest you to give CompoentRegistry a read!

Clone this wiki locally