Настройка плагинов

Предупреждение

Эти документы были написаны для SpongeAPI 7 и, вероятно, устаревшие. Если вы чувствуете, что вы можете помочь обновить их, пожалуйста, отправьте PR!

Файлы конфигурации позволяют плагинам хранить данные, а также позволяют администраторам сервера легко управлять конкретными частями плагина, если вы решите позволить им это. Sponge использует Configurate, чтобы вы могли легко манипулировать файлами конфигурации. На этих страницах объясняется, как задействовать Configurate, чтобы использовать все возможности файлов конфигурации.

Совет

See the official Configurate wiki to gain more in-depth information about working with its components.

Примечание

Sponge makes use of the HOCON configuration format, a superset of JSON, as the default format for saving configuration files. The rest of this guide will assume you are using HOCON as well. See Основы HOCON more for information regarding the HOCON format. Working with different formats is made relatively similar by the Configurate system, so it should not pose too much of an issue if you use an alternate format instead.

Быстрый старт

Создание стандартной конфигурации плагина

Plugins using SpongeAPI have the option to use one or more configuration files. Configuration files allow plugins to store data, and they allow server administrators to customize plugin options (if applicable).

Получение конфигурационного файла плагина по умолчанию

SpongeAPI offers the use of the DefaultConfig annotation on a field or setter method with the type Path to get the default configuration file for your plugin.

If you place the @DefaultConfig annotation on a field with the type ConfigurationLoader<CommentedConfigurationNode> then you can use it to load and save the default config file in the file system. Please keep in mind that the annotated ConfigurationLoader does not use any default config file that you might ship with your jar, unless you explicitly load it.

Аннотация @DefaultConfig требует булевый (логический) параметр sharedRoot. Если sharedRoot установлен на true, то конфигурационный файл будет находиться в общей папке конфигурационных файлов. В этом случае название конфигурационного файла будет ID_плагина.conf (где «ID_плагина» - заданный ID плагина).

Совет

См. plugin-class для получения информации о настройке ID вашего плагина.

If you set sharedRoot to false, the returned pathname will refer to a file named {pluginname}.conf in a directory specific to your plugin.

Если есть сомнения, по поводу выбора значения sharedRoot для Вашего плагина, учитывайте следующее:

  • Если планируете, что конфигурационных файлов будет несколько (для большого плагина), задайте значение false.

  • Если планируете, что конфигурационный файл будет лишь один (простой плагин), задайте значение true.

You can also obtain a Path instance pointing to the config directory instead of a particular file. Just have it injected using the ConfigDir annotation, either with sharedRoot set to false for a plugin specific directory or to true to get the shared configuration directory.

Примечание

While it may be possible to get a File instead of a Path, Configurate (and Sponge) recommend using Path.

Пример - Использование полей @DefaultConfig

import java.nio.file.Path;
import com.google.inject.Inject;
import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.api.config.DefaultConfig;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.loader.ConfigurationLoader;

@Inject
@DefaultConfig(sharedRoot = true)
private Path defaultConfig;

@Inject
@DefaultConfig(sharedRoot = true)
private ConfigurationLoader<CommentedConfigurationNode> configManager;

@Inject
@ConfigDir(sharedRoot = false)
private Path privateConfigDir;

Предупреждение

When your plugin is running for the first time, returned pathnames for configuration files and directories may not yet exist. If you delegate all reading / writing of files to Configurate, you do not need to worry about non-existent paths as the library will handle them appropriately.

Примечание

The use of YAML format (https://yaml.org/spec/1.1/) and JSON format (https://www.json.org/) is also supported, but the preferred config format for Sponge plugins is HOCON. Conversion from YAML (or JSON) to HOCON can be automated by using a YAMLConfigurationLoader (or GsonConfigurationLoader) to load the old config and then saving it using a HoconConfigurationLoader.