0

I am learning javaEE and I read somewhere about the main usage of cdi's was back then first in jsf-managed beans with annotations like @requestscope, @applicationscope, etc.. now in newer javaEE versions the cdi got available everywhere (even in ejb beans) so the question is, how do I have to annotate a class which shall be injected inside my local stateless ejb? I am asking this because the annotations like @RequestScope and all those are from jsf but I am not using jsf. Is @Default enough since its marked as default anyway? Is @Dependent better choice?

@Stateless
public class FooEjb{
@Inject Bar b;
}

// what annotation to put here?
public class Bar {
...
}
dev hedgehog
  • 8,698
  • 3
  • 28
  • 55

2 Answers2

0

Yes you don't need JSF to use CDI in JavaEE.

If you are using CDI without using JSF, use the scope annotations from the javax.enterprise.context package.

@Default is a qualifier which as the name suggests the default qualifier. If you have multiple implementations/instances of the same class in your container, then you can use qualifiers to distinguish.

@Dependent is a scope which is the default scope. This means it will depend on the scope of the class it's injected in. A new instance of a @Dependent class will be injected every time a new instance of the class in which it is injected is created.

To enable CDI you need to put a beans.xml file in WEB-INF directory of your web project or META-INF directory of your EAR or EJB project.

ares
  • 4,283
  • 6
  • 32
  • 63
  • That means every bean is automatically '@Default' and '@Dependent'? If I would have 3 different impl of my bean then there would be 3 times '@Default' therefore I should use '@Alternative', right? – dev hedgehog Jan 26 '17 at 07:28
  • @devhedgehog: Yes every bean in the container is `@Default` and `@Dependent` unless declared otherwise. If you have two implementations then `@Alternative` would be fine, however for more than two you can write your own `@Qualifiers`. https://dzone.com/articles/define-cdi-qualifier – ares Jan 26 '17 at 07:33
  • Ok I understand that so far. Now the question is how to I inject a ejb stateless class without using "@EJB"? – dev hedgehog Jan 26 '17 at 07:36
  • If it's a local interface, you can simply do `@Inject`. – ares Jan 26 '17 at 07:37
0

According to the java ee documentation, no annotation is required in your case. A simple POJO is an injectable bean and receive the @Default annotation. No need to use JSF.

Genoud Magloire
  • 555
  • 6
  • 15