Search code examples
jakarta-eeinterfacecdimanaged-beanmultiple-instances

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)


Solution

  • 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: