12

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)

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Elimination
  • 2,619
  • 4
  • 22
  • 38

1 Answers1

20

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:

Jens Piegsa
  • 7,399
  • 5
  • 58
  • 106