When I inject EJB 3.1 beans into POJO created by @Inject then injection works. When I construct POJO on my own then it doesn't (Glassfish v3). Is it correct behavior?
My classes (in EJB module):
@Singleton
@LocalBean
@Startup
@Named
public class NewSingletonBean {
@PostConstruct
public void init(){
System.out.println("NewSingletonBean INIT");
}
}
_
public class MyPOJO {
@Inject NewSingletonBean newSingletonBean;
public void sth(){
System.out.println("EJB injected into POJO: " + (newSingletonBean != null));
}
}
This does not work:
@Singleton
@LocalBean
@Startup
@DependsOn(value="NewSingletonBean")
public class NewSingletonBean2 {
@Inject NewSingletonBean newSingletonBean;
@PostConstruct
public void init(){
System.out.println("NewSingletonBean2 INIT");
System.out.println("EJB injected into EJB: " + (newSingletonBean != null));
MyPOJO p = new MyPOJO();
p.sth();
}
}
_
And this works OK:
@Singleton
@LocalBean
@Startup
@DependsOn(value="NewSingletonBean")
public class NewSingletonBean2 {
@Inject NewSingletonBean newSingletonBean;
@Inject MyPOJO p;
@PostConstruct
public void init(){
System.out.println("NewSingletonBean2 INIT");
System.out.println("EJB injected into EJB: " + (newSingletonBean != null));
p.sth();
}
}
I'm using NetBeans 7.0.1.
dist directory structure:
│ CDITest.ear
│
└───gfdeploy
└───CDITest
├───CDITest-ejb_jar
│ │ .netbeans_automatic_build
│ │ .netbeans_update_resources
│ │
│ ├───META-INF
│ │ beans.xml
│ │ MANIFEST.MF
│ │
│ └───tries
│ MyPOJO.class
│ NewSingletonBean.class
│ NewSingletonBean2.class
│
├───CDITest-war_war
│ │ index.jsp
│ │
│ ├───META-INF
│ │ MANIFEST.MF
│ │
│ └───WEB-INF
│ └───classes
│ .netbeans_automatic_build
│ .netbeans_update_resources
│
└───META-INF
MANIFEST.MF
Unpacked EAR structure:
│ CDITest-ejb.jar
│ CDITest-war.war
│
└───META-INF
MANIFEST.MF
Unpacked EJB module jar structure:
├───META-INF
│ beans.xml
│ MANIFEST.MF
│
└───tries
MyPOJO.class
NewSingletonBean.class
NewSingletonBean2.class
Is it correct behavior?
The following part might be an answer to your question:
As per CDI 1.0 specification:
3.7. Bean constructors
When the container instantiates a bean class, it calls the bean constructor. The bean constructor is a constructor of the bean class.
The application may call bean constructors directly. However, if the application directly instantiates the bean, no parameters are passed to the constructor by the container; the returned object is not bound to any context; no dependencies are injected by the container; and the lifecycle of the new instance is not managed by the container.
HTH!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With