-
Notifications
You must be signed in to change notification settings - Fork 6
Functions evaluator
To enable function calls, you must enable the org.seedstack.coffig.evaluator.FunctionEvaluator
class. This can be done when building the Coffig instance:
Coffig.builder()
.withProviders(...)
.withEvaluators(new FunctionEvaluator())
.build();
or by registering an evaluator in META-INF/services/org.seedstack.coffig.spi.ConfigurationEvaluator
:
org.seedstack.coffig.evaluator.FunctionEvaluator
Function calls allow to call predefined Java methods from configuration nodes. Function calls use the $fn()
syntax:
symbols: [ '!', '.', '?' ]
message: $greet('World', symbols, 0)
The greet
function is implemented as a method annotated with @org.seedstack.coffig.spi.ConfigFunction
in a class implementing org.seedstack.coffig.spi.ConfigFunctionHolder
:
package org.seedstack.samples.config;
public class GreetFunctionHolder implements ConfigFunctionHolder {
private Coffig coffig;
@Override
public void initialize(Coffig coffig) {
this.coffig = coffig;
}
@ConfigFunction
private String greet(String name, String[] symbols, int index) {
return String.format("Hello %s %s", name, symbols[index]);
}
}
The GreetFunctionHolder
class must be registered with the Java ServiceLoader mechanism,
with the following file:
src/main/resources
└ META-INF
└ services
└ org.seedstack.coffig.spi.ConfigFunctionHolder
containing:
org.seedstack.samples.config.GreetFunctionHolder
In the example above, the node message
will be evaluated to "Hello World!". Parameters are automatically mapped to their
Java type, allowing to pass complex objects to configuration functions. String literals can be passed as parameters by
enclosing them with single quotes. Parameters that reference other nodes must specify their full path.
Function calls can be avoided by escaping the dollar sign with a backslash: \$greet('World', symbols, 0)
will be
evaluated to "$greet('World', symbols, 0)".
Parameters can be other functions calls: $greet('World', $getSymbols(), 0)
will use the return value of the getSymbols()
function call as second parameter.