Внедрение зависимостей
Sponge использует внедрение зависимостей для предоставления экземпляров API плагинам. Внедрение зависимостей позволяет плагинам определить несколько типов API, которые будут использоваться после конструкции (construction).
Временный список внедренных типов
- ConfigDir (аннотация пути или файла)
Used to inject the plugin’s configuration directory:
./mods/
OR./mods/<Plugin#id>/
depending on ConfigDir#sharedRoot()- ConfigurationLoader<CommentedConfigurationNode>
Должен быть аннотирован как
@DefaultConfig
. Используется для внедрения сгенерированногоConfigurationLoader
дляFile
той же аннотации.- DefaultConfig (аннотация пути, ConfigurationLoader’a или файла)
Используется для внедрения специализированного файла конфигурации плагина:
<Plugin#id>.conf
- EventManager
Управляет регистрацией обработчиков событий и диспетчеризацией событий.
- File
Должен быть аннотирован или как
@DefaultConfig`, или как``@ConfigDir
. Основываясь на выбранной аннотации, он будет указывать на файловую ссылку на файл стандартной конфигурации плагина или на директорию, используемую для хранения файлов конфигурации. В прочем, следует предпочитать Path (см. ниже).- Game
The
Game
object is the core accessor of the SpongeAPI.- GameRegistry
Provides an easy way to retrieve types from a
Game
.- GuiceObjectMapperFactory
A tool provided by Configurate to allow easier mapping of objects to configuration nodes. See Serializing Objects for usage.
- Injector
com.google.inject.Injector
is available from Guice, it is the injector that was used to inject your plugin’s dependencies. You can use it to create a child injector with your own module in order to inject your own classes with either the Sponge provided dependencies listed on this page, or configure your own classes- Logger
Used to identify the plugin from which logged messages are sent.
- Path
Must be annotated with either
@DefaultConfig
or@ConfigDir
. Depending on the annotation given this will contain a path reference to the plugins default config file or the directory used for storing configuration files.- PluginContainer
A Plugin class wrapper, used to retrieve information from the annotation for easier use.
- PluginManager
Manages the plugins loaded by the implementation. Can retrieve another plugin’s
PluginContainer
.
Injection Examples
There are a few references which are difficult to get - or, in some cases, impossible - without injection. While these may not be absolutely vital to every plugin, they’re quite frequently used.
Примечание
Remember that it’s almost always best practice to inject your objects within the main class, as it’s instantiated with the Guice injector when the plugin is loaded.
Logger
Совет
View Ведение логов (журналов) и отладка for a complete guide, specifically for the Logger.
Game
The Game
object is the opening for many of the internal functions of the SpongeAPI, from the EventManager
to the
Server and even the Sync/Async Scheduler.
It’s entirely possible to receive the Game
object from within most events, however it is commonly obtained through
an injection.
Пример - поле
import com.google.inject.Inject;
import org.spongepowered.api.Game;
@Inject
private Game game;
Пример - метод
private Game game;
@Inject
private void setGame(Game game) {
this.game = game;
}
Пример - конструктор
For the purpose of this tutorial, «Apple» is the class name.
private Game game;
@Inject
public Apple(Game game) {
this.game = game;
}
Config Directory
The recommended way to obtain your config file is through Guice, along with the ConfigDir annotation.
Совет
If you set sharedRoot
to true
, your ConfigDir
will be the same directory which - potentially - houses
the configuration for other plugins. In most cases where grabbing the ConfigDir
is required, this should be
false
.
Пример - поле
import org.spongepowered.api.config.ConfigDir;
import java.nio.file.Path;
@Inject
@ConfigDir(sharedRoot = false)
private Path configDir;
Пример - метод
private Path configDir;
@Inject
@ConfigDir(sharedRoot = false)
private void setConfigDir(Path configDir) {
this.configDir = configDir;
}
Пример - конструктор
For the purposes of this tutorial, «Orange» is the class name.
private Path configDir;
@Inject
public Orange(@ConfigDir(sharedRoot = false) Path configDir) {
this.configDir = configDir;
}
DefaultConfig
The way that @DefaultConfig
works is very similar to @ConfigDir
. The biggest difference obviously being that
@DefaultConfig
refers to a specific file, where @ConfigDir
refers to a directory.
Совет
View Настройка плагинов for a complete guide, specifically for @DefaultConfig
.