-
- All Known Implementing Classes:
MpConfigProviderResolver.ConfigDelegate
public interface ConfigConfiguration
Immutable tree-structured configuration.Loading Configuration
Load the default configuration using thecreate()method.
UseConfig config = Config.create();Config.Builderto construct a newConfiginstance from one or more specificConfigSources using thebuilder().The application can affect the way the system loads configuration by implementing interfaces defined in the SPI, by explicitly constructing the
Config.Builderwhich assembles theConfig, and by using other classes provided by the config system that influence loading.Some Config SPI Interfaces Class.Method Application-implemented Interface Purpose ConfigSources.create(io.helidon.config.Config)ConfigSourceLoads configuration from a different type of origin. Each ConfigSourceimplementation handles a type of location. Different instances of a givenConfigSourceimplementation represent separate sources of that location type.Config.Builder.addParser(io.helidon.config.spi.ConfigParser)ConfigParserConverts one format of config representation into the corresponding Configtree.Config.Builder.addFilter(io.helidon.config.spi.ConfigFilter)ConfigFilterChanges the Stringrepresentation of each config value from oneStringto another as theConfigtree is built from its sources.OverrideSourcesReplaces config Stringvalues during loading based on their keys. Programs provide overrides in Java property file format on the classpath, at a URL, or in a file, or by invokingOverrideSources.create(java.util.Map<java.lang.String, java.lang.String>)and passing the name-matching expressions and the corresponding replacement value as aMap.Config.Builder.addMapper(Class, Function)Implements conversion from a Confignode (typically with children) to an application-specific Java type.Navigating in a Configuration Tree
Each loaded configuration is a tree ofConfigobjects. The application can access an arbitrary node in the tree by passing its fully-qualified name toget(java.lang.String):
MethodConfig greeting = config.get("greeting");key()always returns fully-qualifiedConfig.Keyof a config node.
These are equivalent ways of obtaining the sameassert greeting.key().toString().equals("greeting")Configinstance, and the two assertions will succeed:
TheConfig name1 = config.get("app.services.svc1.name"); Config name2 = config.get("app").get("services.svc1.name"); Config name3 = config.get("app.services").get("svc1").get("name"); Config name4 = config.get("app").get("services").get("svc1").get("name"); assert name4.key().equals(Key.create("app.services.svc1.name")) assert name1 == name2 == name3 == name4get(java.lang.String)method always returns aConfigobject, even if no configuration is present using the corresponding key. The application can invoke thetype()method to find out the type of the node, represented by one of theConfig.Typeenum values. Theexists()method tells whether or not theConfignode represents existing configuration.
Theif (!config.get("very.rare.prop42").exists()) { // node 'very.rare.prop42' does NOT exist }traverse()method visits all nodes in a subtree. This example gathers all nodes with keys matchinglogging.**.level-- that is, all nodes within the "logging" subtree that have a key ending in "level" and also has a single value:Map<String,String> loggingLevels = config.get("logging") // find "logging" subtree .traverse() // traverse through logging' nodes .filter(node -> node.isLeaf()) // filter leaf values .filter(node -> node.name().equals("level")) // filter key suffix '.level' .collect(Collectors.toMap(Config::key, Config::asString));To retrieve children of a config node use
asNodeList()To get node value, use
as(Class)to access this config node as aConfigValueConverting Configuration Values to Types
Explicit Conversion by the Application
The interpretation of a configuration node, including what datatype to use, is up to the application. To interpret a node's value as a type other thanStringthe application can invoke one of these convenience methods:as<typename>such asasBoolean, asDouble, asInt, etc. which returnConfigValuerepresenting Java primitive data values (boolean, double, int, etc.)The
ConfigValuecan be used to access the value or use optional style methods. The config value provides access to the value in multiple ways. SeeConfigValuefor reference. Basic usages:// throws a MissingValueException in case the config node does not exist long l1 = config.asLong().get(); // returns 42 in case the config node does not exist long l2 = config.asLong().orElse(42L); // invokes the method "timeout(long)" if the value exists config.asLong().ifPresent(this::timeout);as(Class)to convert the config node to an instance of the specified class, if there is a configured mapper present that supports the class.// throws a MissingValueException in case the config node does not exist // throws a ConfigMappingException in case the config node cannot be converted to Long long l1 = config.as(Long.class).get(); // returns 42 in case the config node does not exist // throws a ConfigMappingException in case the config node cannot be converted to Long long l2 = config.as(Long.class).orElse(42L); // invokes the method "timeout(long)" if the value exists // throws a ConfigMappingException in case the config node cannot be converted to Long config.as(Long.class).ifPresent(this::timeout);as(Function)to convert the config node using the function provided. Let's assume there is a methodpublic static Foo create(Config)on a classFoo:// throws a MissingValueException in case the config node does not exist // throws a ConfigMappingException in case the config node cannot be converted to Foo Foo f1 = config.as(Foo::create).get(); // throws a ConfigMappingException in case the config node cannot be converted to Foo Foo f2 = config.as(Foo::create).orElse(Foo.DEFAULT); // invokes the method "foo(Foo)" if the value exists // throws a ConfigMappingException in case the config node cannot be converted to Foo config.as(Foo::create).ifPresent(this::foo);as(GenericType)to convert the config node to an instance of the specified generic type, if there is a configured mapper present that supports the generic type.// throws a MissingValueException in case the config node does not exist // throws a ConfigMappingException in case the config node cannot be converted to Map<String, Integer> Map<String, Integer> m1 = config.as(new GenericType<Map<String, Integer>() {}).get(); // throws a ConfigMappingException in case the config node cannot be converted to Map<String, Integer> Map<String, Integer> m1 = config.as(new GenericType<Map<String, Integer>() {}).orElseGet(Collections::emptyMap); // invokes the method "units(Map)" if the value exists // throws a ConfigMappingException in case the config node cannot be converted to Map<String, Integer> config.as(new GenericType<Map<String, Integer>() {}).ifPresent(this::units);
- invoking the
as(Function)method variants, - adding custom mapping function implementations using the
Config.Builder.addMapper(Class, Function)method, - add custom mapping function using the
Config.Builder.addStringMapper(Class, Function) - registering custom mappers using the Java service loader mechanism. (See
ConfigMapperProviderfor details.)
If there is no explicitly registered mapping function in a
Config.Builderfor converting a given type then the config system throwsConfigMappingException, unless you use the config beans support, that can handle classes that fulfill some requirements (see documentation), such as a public constructor, static "create(Config)" method etc.Handling Multiple Configuration Sources
AConfiginstance, including the defaultConfigreturned bycreate(), might be associated with multipleConfigSources. The config system merges these together so that values from config sources with higher priority have precedence over values from config sources with lower priority.
-
-
Nested Class Summary
Nested Classes Modifier and Type Interface Description static interfaceConfig.BuilderConfigBuilder.static interfaceConfig.ContextContext associated with specificConfignode that allows to access the last loaded instance of the node or to request reloading of whole configuration.static interfaceConfig.KeyObject represents fully-qualified key of config node.static classConfig.TypeConfiguration node types.
-
Field Summary
Fields Modifier and Type Field Description static GenericType<Config>GENERIC_TYPEGeneric type of configuration.
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Default Methods Modifier and Type Method Description <T> ConfigValue<T>as(GenericType<T> genericType)Typed value as aConfigValuefor a generic type.<T> ConfigValue<T>as(Class<T> type)Typed value as aConfigValue.<T> ConfigValue<T>as(Function<Config,T> mapper)Typed value as aConfigValuecreated from factory method.default ConfigValue<Boolean>asBoolean()Boolean typed value.default ConfigValue<Double>asDouble()Double typed value.default ConfigValue<Integer>asInt()Integer typed value.<T> ConfigValue<List<T>>asList(Class<T> type)Returns list of specified type.<T> ConfigValue<List<T>>asList(Function<Config,T> mapper)Returns this node as a list converting each list value using the provided mapper.default ConfigValue<Long>asLong()Long typed value.ConfigValue<Map<String,String>>asMap()Transform all leaf nodes (values) into Map instance.default ConfigValue<Config>asNode()Returns existing current config node as aOptionalinstance orOptional.empty()in case ofConfig.Type.MISSINGnode.ConfigValue<List<Config>>asNodeList()Returns a list of childConfignodes if the node isConfig.Type.OBJECT.default ConfigValue<String>asString()String typed value.static Config.Builderbuilder()Provides aConfig.Builderfor creating aConfiginstance.static Config.Builderbuilder(Supplier<? extends ConfigSource>... configSources)default Config.Contextcontext()Returns theContextinstance associated with the currentConfignode that allows the application to access the last loaded instance of the node or to request that the entire configuration be reloaded.<T> Tconvert(Class<T> type, String value)Convert a String to a specific type.static Configcreate()Returns a new defaultConfigloaded using one of the configuration files available on the classpath and/or using the runtime environment.static Configcreate(Supplier<? extends ConfigSource>... configSources)Creates a newConfigloaded from environment variables, system properties, and the specifiedConfigSources.Configdetach()Returns a copy of theConfignode with no parent.static Configempty()Returns empty instance ofConfig.default booleanexists()Returnstrueif the node exists, whether an object, a list, or a value node.Configget(Config.Key key)Returns the single sub-node for the specified sub-key.default Configget(String key)Returns the single sub-node for the specified sub-key.booleanhasValue()Returnstrueif this configuration node has a direct value.default voidifExists(Consumer<Config> action)Performs the given action with the config node if nodeexists, otherwise does nothing.default booleanisLeaf()Returnstrueif this node exists and is a leaf node (has no children).static Configjust(Supplier<? extends ConfigSource>... configSources)Creates a newConfigloaded from the specifiedConfigSources.Config.Keykey()Returns the fully-qualified key of theConfignode.ConfigMappermapper()The mapper used by this config instance.default Stringname()Returns the last token of the fully-qualified key for theConfignode.default voidonChange(Consumer<Config> onChangeConsumer)Register aConsumerthat is invoked each time a change occurs on whole Config or on a particular Config node.Instanttimestamp()Returns when the configuration tree was created.default Stream<Config>traverse()Iterative deepening depth-first traversal of the node and its subtree as aStream<Config>.Stream<Config>traverse(Predicate<Config> predicate)Iterative deepening depth-first traversal of the node and its subtree as aStream<Config>, qualified by the specified predicate.Config.Typetype()Provides theConfig.Typeof theConfignode.
-
-
-
Field Detail
-
GENERIC_TYPE
static final GenericType<Config> GENERIC_TYPE
Generic type of configuration.
-
-
Method Detail
-
empty
static Config empty()
Returns empty instance ofConfig.- Returns:
- empty instance of
Config.
-
create
static Config create()
Returns a new defaultConfigloaded using one of the configuration files available on the classpath and/or using the runtime environment.The config system loads the default configuration using a default
Config.Builderwhich loads configuration data as described below. In contrast, the application can control how and from where configuration is loaded by explicitly creating and fine-tuning one or moreBuilderinstances itself.- Meta-configuration
Meta-configuration specifies at least one
ConfigSourceorConfig.Builderfrom which the system can load configuration. The config system searches for at most one of the following meta-configuration locations on the classpath, in this order:meta-config.yaml- meta configuration file in YAML formatmeta-config.conf- meta configuration file in HOCON formatmeta-config.json- meta configuration file in JSON formatmeta-config.properties- meta configuration file in Java Properties format
- Configuration
In the absence of meta-configuration the config system loads the default configuration from all of the following sources:
environment variables;system properties- at most one of following locations on the classpath, in this order:
application.yaml- configuration file in YAML formatapplication.conf- configuration file in HOCON formatapplication.json- configuration file in JSON formatapplication.properties- configuration file in Java Properties format
application.*location it finds for which it can locate aConfigParserthat supports the correspondingmedia type.When creating the default configuration the config system detects parsers that were loaded using the
ServiceLoadermechanism or, if it finds none loaded, a built-in parser provided by the config system.
Configinstance which has neither apolling strategynor aretry policy. To set up these and other behaviors the application should create explicitly aConfig.Builder, tailor it accordingly, and then use itsbuildmethod to create theConfiginstance as desired.- Returns:
- new instance of
Config
- Meta-configuration
-
create
@SafeVarargs static Config create(Supplier<? extends ConfigSource>... configSources)
Creates a newConfigloaded from environment variables, system properties, and the specifiedConfigSources.The resulting configuration uses the following sources, in order:
environment variables config source
Can disabled byConfig.Builder.disableEnvironmentVariablesSource()system properties config sourceCan disabled byConfig.Builder.disableSystemPropertiesSource()- Source(s) specified by user in the method.
- Parameters:
configSources- ordered list of configuration sources- Returns:
- new instance of
Config - See Also:
builder(Supplier[]),Config.Builder.sources(List),Config.Builder.disableEnvironmentVariablesSource(),Config.Builder.disableSystemPropertiesSource()
-
builder
@SafeVarargs static Config.Builder builder(Supplier<? extends ConfigSource>... configSources)
Provides aConfig.Builderfor creating aConfigbased on the specifiedConfigSourceinstances.The resulting configuration uses the following sources, in order:
environment variables
Can be disabled by invokingConfig.Builder.disableEnvironmentVariablesSource()system properties config source
Can be disabled by invokingConfig.Builder.disableSystemPropertiesSource()- source(s) passed in the method invocation
- Parameters:
configSources- ordered list of configuration sources- Returns:
- new initialized Builder instance
- See Also:
builder(),create(Supplier[]),Config.Builder.sources(List),Config.Builder.disableEnvironmentVariablesSource(),Config.Builder.disableSystemPropertiesSource()
-
builder
static Config.Builder builder()
Provides aConfig.Builderfor creating aConfiginstance.- Returns:
- new Builder instance
-
just
@SafeVarargs static Config just(Supplier<? extends ConfigSource>... configSources)
Creates a newConfigloaded from the specifiedConfigSources. No other sources will be included.- Parameters:
configSources- ordered list of configuration sources- Returns:
- new instance of
Config - See Also:
builder(Supplier[])
-
context
default Config.Context context()
Returns theContextinstance associated with the currentConfignode that allows the application to access the last loaded instance of the node or to request that the entire configuration be reloaded.- Returns:
- Context instance associated with specific Config node
-
timestamp
Instant timestamp()
Returns when the configuration tree was created.Each config node of single Config tree returns same timestamp.
- Returns:
- timestamp of created instance of whole configuration tree.
- See Also:
context(),Config.Context.timestamp()
-
key
Config.Key key()
Returns the fully-qualified key of theConfignode.The fully-qualified key is a sequence of tokens derived from the name of each node along the path from the config root to the current node. Tokens are separated by
.(the dot character). Seename()for more information on the format of each token.- Returns:
- current config node key
- See Also:
name()
-
name
default String name()
Returns the last token of the fully-qualified key for theConfignode.The name of a node is the last token in its fully-qualified key.
The exact format of the name depends on the
Typeof the containing node:- from a
Config.Type.OBJECTnode the token for a child is the name of the object member; - from a
Config.Type.LISTnode the token for a child is a zero-based index of the element, an unsigned base-10 integer value with no leading zeros.
The ABNF syntax of config key is:
config-key = *1( key-token *( "." key-token ) ) key-token = *( unescaped / escaped ) unescaped = %x00-2D / %x2F-7D / %x7F-10FFFF ; %x2E ('.') and %x7E ('~') are excluded from 'unescaped' escaped = "~" ( "0" / "1" ) ; representing '~' and '.', respectively- Returns:
- current config node key
- See Also:
key(),Config.Key.name()
- from a
-
get
default Config get(String key)
Returns the single sub-node for the specified sub-key.The format of the key is described on
key()method.- Parameters:
key- sub-key of requested sub-node- Returns:
- config node for specified sub-key, never returns
null. - See Also:
get(Key)
-
get
Config get(Config.Key key)
Returns the single sub-node for the specified sub-key.- Parameters:
key- sub-key of requested sub-node- Returns:
- config node for specified sub-key, never returns
null. - See Also:
get(String)
-
detach
Config detach()
Returns a copy of theConfignode with no parent.The returned node acts as a root node for the subtree below it. Its key is the empty string;
"". The original config node is unchanged, and the original and the copy point to the same children.Consider the following configuration:
app: name: Example 1 page-size: 20 logging: app.level = INFO level = WARNINGTheConfiginstancesname1andname2represents same data and in fact refer to the same object:Config name1 = config .get("app") .get("name"); Config name2 = config .get("app") .detach() //DETACHED node .get("name"); assert name1.asString() == "Example 1"; assert name2.asString() == "Example 1"; //DETACHED nodeThe only difference is the key each node returns:assert name1.key() == "app.name"; assert name2.key() == "name"; //DETACHED node
See
asMap()for example of config detaching.- Returns:
- returns detached Config instance of same config node
-
type
Config.Type type()
Provides theConfig.Typeof theConfignode.- Returns:
- the
Typeof the configuration node
-
exists
default boolean exists()
Returnstrueif the node exists, whether an object, a list, or a value node.- Returns:
trueif the node exists
-
isLeaf
default boolean isLeaf()
Returnstrueif this node exists and is a leaf node (has no children).A leaf node has no nested configuration subtree and has a single value.
- Returns:
trueif the node is existing leaf node,falseotherwise.
-
hasValue
boolean hasValue()
Returnstrueif this configuration node has a direct value.This may be a value node (e.g. a leaf) or object node or a list node (e.g. a branch with value). The application can invoke methods such as
as(Class)on nodes that have value.- Returns:
trueif the node has direct value,falseotherwise.
-
ifExists
default void ifExists(Consumer<Config> action)
Performs the given action with the config node if nodeexists, otherwise does nothing.
-
traverse
default Stream<Config> traverse()
Iterative deepening depth-first traversal of the node and its subtree as aStream<Config>.If the config node does not exist or is a leaf the returned stream is empty.
Depending on the structure of the configuration the returned stream can deliver a mix of object, list, and leaf value nodes. The stream will include and traverse through object members and list elements.
- Returns:
- stream of deepening depth-first sub-nodes
-
traverse
Stream<Config> traverse(Predicate<Config> predicate)
Iterative deepening depth-first traversal of the node and its subtree as aStream<Config>, qualified by the specified predicate.If the config node does not exist or is a leaf the returned stream is empty.
Depending on the structure of the configuration the returned stream can deliver a mix of object, list, and leaf value nodes. The stream will include and traverse through object members and list elements.
The traversal continues as long as the specified
predicateevaluates totrue. When the predicate evaluates tofalsethe node being traversed and its subtree will be excluded from the returnedStream<Config>.- Parameters:
predicate- predicate evaluated on each visitedConfignode to continue or stop visiting the node- Returns:
- stream of deepening depth-first subnodes
-
convert
<T> T convert(Class<T> type, String value) throws ConfigMappingException
Convert a String to a specific type. This is a helper method to allow for processing of default values that cannot be typed (e.g. in annotations).- Type Parameters:
T- type- Parameters:
type- type of the propertyvalue- String value- Returns:
- instance of the correct type
- Throws:
ConfigMappingException- in case the String provided cannot be converted to the type expected- See Also:
as(Class)
-
mapper
ConfigMapper mapper()
The mapper used by this config instance.- Returns:
- configuration mapper
-
as
<T> ConfigValue<T> as(GenericType<T> genericType)
Typed value as aConfigValuefor a generic type. If appropriate mapper exists, returns a properly typed generic instance.Example:
ConfigValue<Map<String, Integer>> myMapValue = config.as(new GenericType<Map<String, Integer>>(){}); myMapValue.ifPresent(map -> { Integer port = map.get("service.port"); }- Type Parameters:
T- type of the returned value- Parameters:
genericType- a (usually anonymous) instance of generic type to prevent type erasure- Returns:
- properly typed config value
-
as
<T> ConfigValue<T> as(Class<T> type)
Typed value as aConfigValue.- Type Parameters:
T- type- Parameters:
type- type class- Returns:
- typed value
- See Also:
ConfigValue.map(Function),ConfigValue.supplier(),ConfigValue.get(),ConfigValue.orElse(Object)
-
as
<T> ConfigValue<T> as(Function<Config,T> mapper)
Typed value as aConfigValuecreated from factory method. To convert from String, you can useconfig.asString().as(Function).- Type Parameters:
T- type- Parameters:
mapper- method to create an instance from config- Returns:
- typed value
-
asBoolean
default ConfigValue<Boolean> asBoolean()
Boolean typed value.- Returns:
- typed value
-
asString
default ConfigValue<String> asString()
String typed value.- Returns:
- typed value
-
asInt
default ConfigValue<Integer> asInt()
Integer typed value.- Returns:
- typed value
-
asLong
default ConfigValue<Long> asLong()
Long typed value.- Returns:
- typed value
-
asDouble
default ConfigValue<Double> asDouble()
Double typed value.- Returns:
- typed value
-
asList
<T> ConfigValue<List<T>> asList(Class<T> type) throws ConfigMappingException
Returns list of specified type.- Type Parameters:
T- type of list elements- Parameters:
type- type class- Returns:
- a typed list with values
- Throws:
ConfigMappingException- in case of problem to map property value.
-
asList
<T> ConfigValue<List<T>> asList(Function<Config,T> mapper) throws ConfigMappingException
Returns this node as a list converting each list value using the provided mapper.- Type Parameters:
T- type of list elements- Parameters:
mapper- mapper to convert each list node into a typed value- Returns:
- a typed list with values
- Throws:
ConfigMappingException- in case the mapper fails to map the values
-
asNode
default ConfigValue<Config> asNode()
Returns existing current config node as aOptionalinstance orOptional.empty()in case ofConfig.Type.MISSINGnode.- Returns:
- current config node as a
Optionalinstance orOptional.empty()in case ofConfig.Type.MISSINGnode.
-
asNodeList
ConfigValue<List<Config>> asNodeList() throws ConfigMappingException
Returns a list of childConfignodes if the node isConfig.Type.OBJECT. Returns a list of element nodes if the node isConfig.Type.LIST. ThrowsMissingValueExceptionif the node isConfig.Type.MISSING. Otherwise, if node isConfig.Type.VALUE, it throwsConfigMappingException.- Returns:
- a list of
Config.Type.OBJECTmembers or a list ofConfig.Type.LISTmembers - Throws:
ConfigMappingException- in case the node isConfig.Type.VALUE
-
asMap
ConfigValue<Map<String,String>> asMap() throws MissingValueException
Transform all leaf nodes (values) into Map instance.Fully qualified key of config node is used as a key in returned Map.
Detachconfig node before transforming to Map in case you want to cut current Config node key prefix.Let's say we work with following configuration:
app: name: Example 1 page-size: 20 logging: app.level = INFO level = WARNINGMapapp1contains two keys:app.name,app.page-size.Map<String, String> app1 = config.get("app").asMap();Detachingappconfig node returns new Config instance with "reset" local root.
MapMap<String, String> app2 = config.get("app").detach().asMap();app2contains two keys withoutappprefix:name,page-size.- Returns:
- new Map instance that contains all config leaf node values
- Throws:
MissingValueException- in case the node isConfig.Type.MISSING.- See Also:
traverse(),detach()
-
onChange
default void onChange(Consumer<Config> onChangeConsumer)
Register aConsumerthat is invoked each time a change occurs on whole Config or on a particular Config node.A user can subscribe on root Config node and then will be notified on any change of Configuration. You can also subscribe on any sub-node, i.e. you will receive notification events just about sub-configuration. No matter how much the sub-configuration has changed you will receive just one notification event that is associated with a node you are subscribed on. If a user subscribes on older instance of Config and ones has already been published the last one is automatically submitted to new-subscriber.
Note: It does not matter what instance version of Config (related to single
Config.Builderinitialization) a user subscribes on. It is enough to subscribe just on single (e.g. on the first) Config instance. There is no added value to subscribe again on new Config instance.- Parameters:
onChangeConsumer- consumer invoked on change
-
-