Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting all beans of the same type with CDI

Suppose we have a package foos containing classes, which all of them implements some IFoo.

We also have a class, Baz which contains a data-member, List<IFoo> fooList. Is it possible to inject dynamically all those IFoo classes into fooList?

By the way, is it a common practice? (I'm new with the DI concept)

like image 489
Elimination Avatar asked Feb 13 '16 16:02

Elimination


People also ask

What are CDI managed beans?

But what is a CDI bean? A CDI bean is a POJO, plain old java object, that has been automatically instantiated by the CDI container, and is injected into all, and any qualifying injection points in the application. The CDI container initiates the bean discovery process during deployment.

How can we inject the beans?

In order to use the beans you create, you inject them into yet another bean that can then be used by an application, such as a JavaServer Faces application. For example, you might create a bean called Printer into which you would inject one of the Greeting beans: import javax. inject.

How does an injected annotation work?

Injectable constructors are annotated with @Inject and accept zero or more dependencies as arguments. @Inject can apply to at most one constructor per class. @Inject is optional for public, no-argument constructors when no other constructors are present. This enables injectors to invoke default constructors.


1 Answers

Use the javax.enterprise.inject.Instance interface to dynamically obtain all instances of Foo:

import javax.annotation.PostConstruct;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;

public class Baz {

    @Inject
    Instance<Foo> foos;

    @PostConstruct
    void init() {
        for (Foo foo : foos) {
            // ...
        }
    }
}

This totally makes sense, e.g. if you want to merge the results of multiple service provider implementations. You find a good study example here.

See also:

  • JSR-000346 Contexts and Dependency Injection for JavaTM EE 1.2,
    Section 5.6. Programmatic lookup
like image 130
Jens Piegsa Avatar answered Sep 21 '22 11:09

Jens Piegsa