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.
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:
You're facing a classic bootstrapping problem, how to move from non-container-managed code into container-managed code. Your options are:
BeanProvider.getContextualReference(Test.class, false);
)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.
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