Configurators and Intercept Producers

In CDI 2.0, it is possible to add Interceptor to a producer programmatically.

For example, there is a POJO.

public class Greeter {

    public Greeter() {
    }

    public void say(String name) {
        System.out.println("Hi, " + name);
    }
}

We want to count the number of calling the method.

Create a Counted qualifier and CountedInterceptor interceptor class.

@Inherited
@InterceptorBinding
@Retention(RUNTIME)
@Target({METHOD, TYPE})
public @interface Counted {

    public static final class Literal extends AnnotationLiteral<Counted> implements Counted {

        public static final Literal INSTANCE = new Literal();

        private static final long serialVersionUID = 1L;

    }
}

The counting service is done by Counter.

Now put all together.

Verify it works as expected.

Grab the source codes from my GitHub account, and have a try.

Last updated

Was this helpful?