Singleton Reference
The instance of a class can be used directly as a configuration value if this class implements the singleton pattern. In this case, the configuration property must be annotated with @InstanceFormat. In the configuration, a singleton matching the type of the property can then be selected via the class name.
For example, the following configuration allows the selection of a Renderers:
public interface MyConfig extends ConfigurationItem {
@InstanceFormat
Renderer getRenderer();
}
Renderer here is an interface for an implementation that outputs a passed object to HTML, for example. If the application has multiple Renderer implementations, the configuration can select one of the renderers by its class name:
<config
renderer="my.app.MyRenderer"
>
</config>
For this, the MyRenderer class only needs to implement the singleton pattern:
public class MyRenderer implements Renderer {
/** Singleton {@link MyRenderer}. */
public MyRenderer INSTANCE = new MyRenderer();
private MyRenderer() {}
@Override
public void render(...) {
// Do what a Renderer has to do.
}
}
The Renderer-singleton MyRenderer must define a public static final constant INSTANCE that contains a Renderer. Then the singleton instance can be referenced in the configuration via the class name of the singleton class.