When should CDI injection in POJO work? (GlassFish v3)

When I embed EJB 3.1 beans in a POJO created using @Inject, then the injection works. When I build POJO on my own, it is not (Glassfish v3). Is this the right behavior?

My classes (in the 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 one 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 one works fine :

 @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 am using NetBeans 7.0.1.

Directory structure

dist:

 CDITest.ear │ └───gfdeploy └───CDITest ├───CDITest-ejb_jar │ │ .netbeans_automatic_build │ │ .netbeans_update_resources │ │ │ ├───META-INF │ │ beans.xml │ │ MANIFEST.MF │ │ │ └───triesMyPOJO.classNewSingletonBean.classNewSingletonBean2.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.jarCDITest-war.war │ └───META-INF MANIFEST.MF 

EJB Open Package Container Structure:

 ├───META-INFbeans.xmlMANIFEST.MF │ └───tries MyPOJO.class NewSingletonBean.class NewSingletonBean2.class 

Is this behavior right?

+4
source share
2 answers

The following part may be the answer to your question:

According to CDI 1.0 specification :

3.7. Bean Constructors

When the container instantiates the Bean class, it calls the bean constructor. The Bean constructor is a constructor of the Bean class.

An application can directly reference Bean constructors. However , if the application directly creates an instance of a bean , the parameters are not passed to the designer by the container; the returned object is not related in any context; no dependencies are entered by the container ; and also the life cycle of a new instance is not managed by the container.

NTN!

+11
source

This is the correct behavior, because DI only works for container-managed beans, not for those you created yourself.

+4
source

Source: https://habr.com/ru/post/1381664/


All Articles