Skip to main content

VarResolvers and VarResolverSessions

The main class for performing variable resolution is VarResolver. A resolver holds a set of Var classes and context objects, and replaces each $X{key} in a string with the value its variable produces.

When to use it​

Use your own VarResolver when you need variables beyond the defaults, or variables that depend on application objects such as a Config. For plain $S{...} and $E{...} lookups, the shared VarResolver.DEFAULT is enough. Resolvers are immutable; to add variables, copy an existing one with copy() and build the copy.

Example​

import org.apache.juneau.commons.svl.*;

public class VarResolverExample {

// A bean that a variable can look up through the session.
public static class Greeting {
public String text = "Hello";
}

// The $G{name} variable reads the Greeting bean from the session.
public static class GreetingVar extends SimpleVar {
public GreetingVar() {
super("G");
}

@Override
public String resolve(VarResolverSession session, String key) {
return session.getBean(Greeting.class).map(g -> g.text).orElse("Hi") + ", " + key;
}
}

public static void main(String[] args) throws Exception {
// Copy the default resolver (which has $S and $E), add $G, and register the bean for all sessions.
VarResolver resolver = VarResolver.DEFAULT
.copy()
.vars(GreetingVar.class)
.bean(Greeting.class, new Greeting())
.build();

System.out.println(resolver.resolve("$G{World}! Java is $S{java.specification.version}."));

// A session can override a bean for one resolution only.
Greeting formal = new Greeting();
formal.text = "Good day";
System.out.println(resolver.createSession().bean(Greeting.class, formal).resolve("$G{World}"));
}
}

Two methods are provided for resolving variables:

VarResolverresolve(String)resolveTo(String,Writer)

Options​

Var resolvers can rely on the existence of other objects. For example, ConfigVar relies on the existence of a Config. This is accomplished through the following methods:

VarResolver.Builderbean(Class<T>, T) - Specify a bean for all sessions.VarResolverSessionbean(Class<T>, T) - Specify a bean for this session.

Beans are accessible through the following method:

VarResolverSession.getBean(Class)
Builder methodEffect
defaultVars()Add the default variables ($S, $E and the others). VarResolver.DEFAULT already has them.
vars(Class...) / vars(Var...)Add variable classes or instances.
functions(...) / defaultFunctions()Add #{...} functions; see Simple Variable Language.
bean(Class, T)Register a bean that variables read through the session.
build()Create the resolver.

Var resolvers can be cloned and extended by using the VarResolver.copy() method. Cloning a resolver will copy it's Var class names and context objects.

See also​