Entering all beans of the same type with CDI

Suppose we have a package fooscontaining classes, all of which implement some IFoo.

We also have a class Bazthat contains a data item List<IFoo> fooList. Is it possible to dynamically inject all of these classes IFoointo fooList?

By the way, is this a common practice? (I'm new to DI concept)
+4
source share
1 answer

Use the interface javax.enterprise.inject.Instanceto dynamically retrieve all instances 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) {
            // ...
        }
    }
}

, . . .

. :

+7

Source: https://habr.com/ru/post/1628645/


All Articles