I would like to know if I can combine the ServiceLoader
with EJB and injection from Java EE 6.
Imagine I have an interface ServiceI
that can be implemented by two EJB stateless beans BeanA
and BeanB
.
If I register these two classes in the MEAT-INF/services
they will be instantiated in the Java SE way, rather than being managed by the Application Container (like when you use @Inject
). This means that annotations like @Inject
or @PostConstruct
won't be resolved.
Is it possible to have something like a ServiceLoader
which would allow me to go through EJB beans implementing a given interface and returning one based on some criteria?
I have found a solution.
If both beans implements the Service
interface you can do the following:
@Inject
private javax.enterprise.inject.Instance.Instance<Service> services
services
implements Iterator<Service>
and will allow to cycle through all the beans that implement the Service
interface.
Then you can choose one of the implementations based on some criteria and you have the equivalent of ServiceLoader
for EJB!