Skip to content
This repository has been archived by the owner on Nov 18, 2020. It is now read-only.

Custom Annotations

Mahmoud Ben Hassine edited this page Jun 8, 2017 · 8 revisions

With Easy Props, you can write your own annotations to load configuration properties from a custom location. The following steps describe how to create your own annotation and how to use it with Easy Props.

Create custom annotation

First, you need to create your annotation with all the necessary information about where to load properties, which property to load, default values, etc. You can see examples of how built-in annotations are defined in the org.jeasy.props.annotations package.

Implement the AnnotationProcessor interface

The AnnotationProcessor interface allows you to specify how to process your annotation to load all the necessary parameters specified by the user.

The following is the definition of this interface:

public interface AnnotationProcessor<T extends Annotation> {

    /**
     * Process an annotation of type T.
     *
     * @param annotation the annotation to process.
     * @param field      the target field
     * @return Return the object to set in the annotated field or null if the value should be ignored
     * @throws AnnotationProcessingException thrown if an exception occurs during annotation processing
     */
    Object processAnnotation(final T annotation, final Field field) throws AnnotationProcessingException;

}

You can see some examples of how the built-in annotations are processed in the org.jeasy.props.processors package.

Register the annotation processor within Easy Props

To register your custom annotation processor within Easy Props, you can use the PropertiesInjectorBuilder API as follows:

//Instantiate a properties injector and register custom annotation processor
PropertiesInjector propertiesInjector = new PropertiesInjectorBuilder()
   .registerAnnotationProcessor(MyAnnotation.class, myAnnotationProcessor)
   .build();

Now you can annotate any field with your annotation and Easy Props will automatically use the registered annotation processor to load the value, convert it to the field type and set it to the field value.