Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can @Inject be used in a pojo

I am trying to use and understand CDI, when I use @Inject in a simple pojo class, it throws me NPE.

example Greeting.java

public Class Greeting {
 public String greet() {
   System.out.println("Hello");
 }
}

Test.java

 import javax.inject.Inject;
 public class Test {
   @Inject 
   private Greeting greeting;

   public void testGreet() {
    greeting.testGreet();
   }
}

When I call testGreet() it throws NPE, why is the greeting instance null. Does @Inject way of adding dependency only be used in container managed bean? Note: jar is not the problem here.

like image 380
Sand Avatar asked Mar 15 '23 07:03

Sand


1 Answers

TL;DR: @Inject-annotated fields are only populated for container-instantiated beans.

Long version: The CDI container provides you a lot of utilities for easily injecting dependencies to your beans, but it doesn't work by magic. The container can only populate the annotated fields of a client bean if the client bean itself was instantiated by the container. When the container is instantiating the object the sequence of events is as follows:

  1. Your bean's constructor is called.
  2. @Inject-annotated fields (and some other annotations, @PersistenceContext and @EJB for instance) are populated.
  3. @PostConstruct-annotated no-args method is called.
  4. Your bean is finished.

You're facing a classic bootstrapping problem, how to move from non-container-managed code into container-managed code. Your options are:

  1. Get access to an instance of BeanManager from your JavaEE container via JNDI lookup. This is technical and a bit clumsy.
  2. Use a CDI extension library such as Apache DeltaSpike. (Example: BeanProvider.getContextualReference(Test.class, false);)
  3. Modify your application to start in a situation where you can inject your Test class rather than calling new Test();. This can be done for example by setting up a startup singleton ejb, which calls your test in it's @PostConstruct-annotated initialisation.

Hope this helps.

like image 65
jvalli Avatar answered Mar 24 '23 19:03

jvalli