Saturday, October 3, 2015

type-safe configs in one minute

within the last months i heard about more and more projects which move to cdi.
an important aspect of cdi is the type-safe injection including type-safe qualifiers and many other concepts based on type-safety.

"surprisingly" type-safe concepts get ignored quite often when it comes to accessing config-values.
however, there is no technical limitation here. in fact creating even generic approaches for type-safe configs can be easy once the implementation is based on deltaspike.

-> like with many other topics my answer is something like:
"use deltaspike and it's way easier."

in case of config-approaches, deltaspike provides several flexible and extensible concepts.
e.g. the upcoming chapter of will also describe some of them in detail.

beyond that it's easy to implement your own concepts based on mechanisms provided by deltaspike.
the following listing illustrates how to implement your own type-safe config.

this implementation is based on the partial-bean module of (@TypeSafeConfig is annotated with @org.apache.deltaspike.partialbean.api.PartialBeanBinding). in a second step it's required to annotate an implementation of java.lang.reflect.InvocationHandler with our own binding-annotation (see @TypeSafeConfig) and implement the logic to load and parse the config-values. in our example we delegate the lookup of the config-values to ConfigResolver#getProjectStageAwarePropertyValue. ConfigResolver is provided by deltaspike and allows to integrate even custom config-sources easily.

with those two simple classes, we can create custom type-safe configs by just creating interfaces and annotating them with our own binding-annotation (see @TypeSafeConfig). the following listings show two examples how to define and use such a custom config (see AppConfig and BatchConfig).

the last snippet shows how to inject and use both configs in any cdi-bean. in the illustrated example we use them in CustomBatchStarter, which is a cdi-enabled implementation of org.quartz.Job (see @org.apache.deltaspike.scheduler.api.Scheduled).