Injection de Dépendances
Lors de la création de votre classe de plugin, Sponge utilise une technique appelée « Injection de Dépendances » pour fournir des objets API à la classe principale de votre plugin. Certains de ces objets, tels que les « Loggers » et les chargeurs de configuration, sont spécifiques à votre plugin et réduisent le code que vous devez écrire pour effectuer certaines de ces tâches.
Avertissement
Sponge ne fait de l’injection que sur la classe principale de votre plugin. L’utilisation de @Inject
sur d’autres classes ne fonctionnera pas à moins que vous n’injectiez un Injector
dans votre classe principale, puis utilisiez cela pour créer d’autres classes.
Injections Simples
Les champs ou les paramètres de constructeur des types suivants peuvent être annotés avec @com.google.inject.Inject
pour demander à Sponge de fournir des objets simples.
Les objets suivants sont les mêmes, quel que soit le plugin qui demande l’injection :
Les types suivants renvoient une instance appropriée pour le plugin :
PluginContainer - renvoie le conteneur de plugin associé au plugin dans lequel il est injecté
org.apache.logging.log4j.Logger
- returns the logger associated with the plugin it is being injected into
Example: Injecting the Plugin Specific Logger and PluginContainer
We can signal to Sponge that you want to inject the logger in one of two ways, field or constructor injection. All simple injections work the same way in Sponge.
For field injection, you must annotate non-final fields with the @Inject
annotation, as in the example below:
import com.google.inject.Inject;
import org.apache.logging.log4j.Logger;
@Inject
private Logger logger;
@Inject
private PluginContainer pluginContainer;
For constructor injection, you must create a constructor, annotate it with @Inject
, and add the objects you
want injecting as parameters, as in the example below:
import com.google.inject.Inject;
import org.apache.logging.log4j.Logger;
// For the purpose of this example, "Banana" is the class name
private final Logger logger;
private final PluginContainer pluginContainer;
@Inject
public Banana(Logger logger, PluginContainer pluginContainer) {
this.logger = logger;
this.pluginContainer = pluginContainer;
}
In both of these examples, the logger
field will contain a Sponge provided logger and the pluginContainer
field
will contain the plugin’s PluginContainer
after the object is constructed.
Configurate Injections
Astuce
View Configuration des plugins for a guide to configuration, specifically using the @DefaultConfig
annotation.
Sponge is also able to inject Configurate specific objects into your plugin class, set up with suggested locations for your plugin configuration. These injections require an additional annotation on your injected type, which will be either ConfigDir or DefaultConfig, dependent on your use case.
The DefaultConfig
Annotation
The DefaultConfig annotation is used to resolve a file location. DefaultConfig
has a parameter
sharedRoot
, which alters the file that it points to (where <pluginid>
is your plugin’s ID):
If
sharedRoot
isfalse
, the annotation will point to the fileconfig/<pluginid>/<pluginid>.conf
.If
sharedRoot
istrue
, the annotation will point to the fileconfig/<pluginid>.conf
.
The DefaultConfig
annotation can be applied on the following types:
ConfigurationLoader<CommentedConfigurationNode>
- provides a configuration loader that will load and save a HOCON file from the resolved file locationConfigurationReference<CommentedConfigurationNode>
- provides a ConfigurationReference that will load and save a HOCON file from the resolved file locationPath
- stores the path to the file location, useful if you wish to use a different file format for your configuration (such as YAML).
Example Injection
The following example injects the HOCON configuration loader and the path it is pointing to via field injection.
import com.google.inject.Inject;
import org.spongepowered.api.config.DefaultConfig
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.loader.ConfigurationLoader;
@Inject
@DefaultConfig(sharedRoot = false)
private ConfigurationLoader<CommentedConfigurationNode> loader;
@Inject
@DefaultConfig(sharedRoot = false)
private Path configFilePath;
Most users will only require the provided loader
, which can then be interacted with in the normal way.
The ConfigDir
annotation
The ConfigDir annotation is used to resolve a folder. The sharedRoot
parameter works as follows
(where <pluginid>
is your plugin’s ID):
If
sharedRoot
isfalse
, the annotation will point to the fileconfig/<pluginid>/
.If
sharedRoot
istrue
, the annotation will point to the fileconfig/
.
The ConfigDir
annotation can only be applied on the Path
type to retrive this directory. It is generally most
useful for plugins that require multiple configuration files, providing the directory to place them rather than a
single file.
Full List of injectables
Type |
Description |
---|---|
PluginContainer |
Your plugin’s container |
Logger |
Your plugin’s log4j logger |
System.Logger |
Your plugin’s Java Logger |
Path |
Your plugin’s config location, use the |
TypeSerializerCollection |
Your plugin’s specific TypeSerializer’s |
ConfigurationLoader |
Your plugin’s config loader, use the |
ConfigurationReference |
Your plugin’s config reference, use the |
Game |
The Sponge global game instance |
MinecraftVersion |
The minecraft version the server is running |
ChannelManager |
The server’s channel manager |
PluginManager |
the server’s plugin manager |
ConfigManager |
the server’s configuration file manager |
MetricsConfigManager |
the server’s metric configurations manager |
ServiceProvider.GameScoped |
The initial service provider for the server |
FactoryProvider |
Not something plugins typically use |
BuilderProvider |
Not something plugins typically use |
Path |
Shared configuration path, used when |