CDI Instances with Interfaces

Creating CDI Instances using interfaces

Recently, I need to create some strategies using CDI. For instance, all classes have common interfaces and CDI create, initialize and turn available for use.

Using Quarkus, follow the example.

First, create the interface:

public interface HttpMechanism {
    void validate();
}

Secondly, we create some implementations to interface:

@ApplicationScoped
public class FilterA implements HttpMechanism {

    @Override
    public void validate() {
        System.out.println("Filter A");
    }
}

@ApplicationScoped
public class FilterB implements HttpMechanism {

    @Override
    public void validate() {
        System.out.println("Filter B");
    }
}

@ApplicationScoped
public class FilterC implements HttpMechanism {

    @Override
    public void validate() {
        System.out.println("Filter C");
    }
}

Now, the magic using a simple Http filter:

@PreMatching
@Provider
public class Filter implements ContainerRequestFilter {

    @Inject
    @Any
    Instance<HttpMechanism> instances;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        for (HttpMechanism instance: instances) {
            instance.validate();
        }
    }
}

How this works? Simple: this filter will intercept all calls and call all filters.

Link to github.

and that’s all folks!

If you have any doubts, problems or suggestions, just leave a message.

No Comments Yet