-
Notifications
You must be signed in to change notification settings - Fork 10
Service
Service is inherited from BaseContainerObject
, it's a single instance ContainerObject that doesn't have a parent. For example, PlayerManager
is a very common instance for Bukkit plugins, usually it purpose is to handle Player related stuff, and it's mostly single instance only. For the example, it fits very well for a Service structure.
To made a Service, it's simple. First create that class that you want to be Service, and add the annotation @io.fairyproject.container.Service
on top of it, and you've successfully made a Service!
package io.fairyproject.examplePlugin;
import io.fairyproject.container.Service;
@Service
public class ExampleService {
}
On runtime, Fairy will scan through every classes in your main package (which is what you set in gradle extension), so there is no need to reference the Service anywhere else in order to initialize it.
In further example, I want the service to store some data and having function to add/remove/read that datas:
package io.fairyproject.examplePlugin;
import io.fairyproject.container.PostInitialize;
import io.fairyproject.container.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@Service
public class ExampleService {
private Map<UUID, String> dataByUuid;
private UUID mainUuid;
@PostInitialize
public void onPostInitialize() {
this.dataByUuid = new HashMap<>(); // You can do it directly on the field too, this is just an example.
this.mainUuid = UUID.randomUUID();
this.add(this.mainUuid, "helloWorld");
}
public UUID getMainUuid() {
return this.mainUuid;
}
public void add(UUID uuid, String data) {
this.dataByUuid.put(uuid, data);
}
public void remove(UUID uuid) {
this.dataByUuid.remove(uuid);
}
public String get(UUID uuid) {
return this.dataByUuid.get(uuid);
}
}
Now we have the Service ready to use, to start using this service we can simply use io.fairyproject.container.Containers.get(ExampleService.class)
to get and instance.
This is not the only way to get ContainerObject instance, there are more such as
ContainerConstructor
andAutowired
package io.fairyproject.examplePlugin;
import io.fairyproject.container.Containers;
import io.fairyproject.plugin.Plugin;
import java.util.UUID;
public class ExamplePlugin extends Plugin {
@Override
public void onPluginEnable() {
System.out.println("Hello World!");
final ExampleService exampleService = Containers.get(ExampleService.class);
System.out.println(exampleService.get(exampleService.getMainUuid()));
UUID uuid = UUID.randomUUID();
exampleService.add(uuid, "test");
}
}
It's depends on you, you can keep it like how you name it before (like XXXXXManager
, XXXXXHandler
etc). But in official fairy project, we used to call XXXXXService
.