Configuration
Immutable tree-structured configuration.Loading Configuration
Load the default configuration using thecreate() method.
Config config = Config.create();
Use Config.Builder to construct a new Config instance
from one or more specific ConfigSources using the builder().
The application can affect the way the system loads configuration by
implementing interfaces defined in the SPI, by explicitly constructing the
Config.Builder which assembles the Config, and by using other
classes provided by the config system that influence loading.
| Class.Method | Application-implemented Interface | Purpose |
|---|---|---|
ConfigSources.create(io.helidon.config.Config) |
ConfigSource |
Loads configuration from a different type of origin. Each
ConfigSource implementation handles a type of location. Different
instances of a given ConfigSource implementation represent separate
sources of that location type. |
Config.Builder.addParser(io.helidon.config.spi.ConfigParser) |
ConfigParser |
Converts one format of config representation into the corresponding
Config tree.
|
Config.Builder.addFilter(io.helidon.config.spi.ConfigFilter) |
ConfigFilter |
Changes the String representation of each config value from one
String to another as the Config tree is built from its
sources. |
OverrideSources |
Replaces config String values 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 invoking OverrideSources.create(java.util.Map<java.lang.String, java.lang.String>) and passing
the name-matching expressions and the corresponding replacement value as a
Map. |
|
Config.Builder.addMapper(Class, Function) |
Implements conversion from a Config node (typically with
children) to an application-specific Java type. |
Navigating in a Configuration Tree
Each loaded configuration is a tree ofConfig objects. The
application can access an arbitrary node in the tree by passing its
fully-qualified name to get(java.lang.String):
Config greeting = config.get("greeting");
Method key() always returns fully-qualified
Config.Key of a config node.
assert greeting.key().toString().equals("greeting")
These are equivalent ways of obtaining the same Config
instance, and the two assertions will succeed:
Config 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 == name4
The get(java.lang.String) method always returns a Config object, even
if no configuration is present using the corresponding key. The application
can invoke the type() method to find out the type of the node,
represented by one of the Config.Type enum values. The exists()
method tells whether or not the Config node represents existing
configuration.
if (!config.get("very.rare.prop42").exists()) {
// node 'very.rare.prop42' does NOT exist
}
The traverse() method visits all nodes in a subtree. This
example gathers all nodes with keys matching logging.**.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 a ConfigValue
Converting 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 thanString the 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.Builder for converting a given type then the config system
throws ConfigMappingException, 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
AConfig instance, including the default Config returned by
create(), might be associated with multiple ConfigSources. 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 ClassesModifier and TypeInterfaceDescriptionstatic interfaceConfigBuilder.static interfaceContext associated with specificConfignode that allows to access the last loaded instance of the node or to request reloading of whole configuration.static interfaceObject represents fully-qualified key of config node.static enumConfiguration node types. -
Field Summary
Fields -
Method Summary
Modifier and TypeMethodDescription<T> ConfigValue<T>as(GenericType<T> genericType) Typed value as aConfigValuefor a generic type.<T> ConfigValue<T>Typed value as aConfigValue.<T> ConfigValue<T>Typed value as aConfigValuecreated from factory method.default ConfigValue<Boolean>Boolean typed value.default ConfigValue<Double>asDouble()Double typed value.default ConfigValue<Integer>asInt()Integer typed value.<T> ConfigValue<List<T>>Returns list of specified type.<T> ConfigValue<List<T>>Returns this node as a list converting each list value using the provided mapper.default ConfigValue<Long>asLong()Long typed value.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.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 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.detach()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.get(Config.Key key) Returns the single sub-node for the specified sub-key.default ConfigReturns the single sub-node for the specified sub-key.booleanhasValue()Returnstrueif this configuration node has a direct value.default voidPerforms 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.key()Returns the fully-qualified key of theConfignode.mapper()The mapper used by this config instance.default Stringname()Returns the last token of the fully-qualified key for theConfignode.default voidRegister aConsumerthat is invoked each time a change occurs on whole Config or on a particular Config node.Returns when the configuration tree was created.traverse()Iterative deepening depth-first traversal of the node and its subtree as aStream<Config>.Iterative deepening depth-first traversal of the node and its subtree as aStream<Config>, qualified by the specified predicate.type()Provides theConfig.Typeof theConfignode.
-
Field Details
-
GENERIC_TYPE
Generic type of configuration.
-
-
Method Details
-
empty
Returns empty instance ofConfig.- Returns:
- empty instance of
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
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
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
Provides aConfig.Builderfor creating aConfiginstance.- Returns:
- new Builder instance
-
just
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:
-
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:
-
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
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:
- from a
-
get
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
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:
-
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
Performs the given action with the config node if nodeexists, otherwise does nothing. -
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
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
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:
-
mapper
ConfigMapper mapper()The mapper used by this config instance.- Returns:
- configuration mapper
-
as
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
Typed value as aConfigValue.- Type Parameters:
T- type- Parameters:
type- type class- Returns:
- typed value
- See Also:
-
as
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
Boolean typed value.- Returns:
- typed value
-
asString
String typed value.- Returns:
- typed value
-
asInt
Integer typed value.- Returns:
- typed value
-
asLong
Long typed value.- Returns:
- typed value
-
asDouble
Double typed value.- Returns:
- typed value
-
asList
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
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
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
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
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:
-
onChange
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
-