Reputation: 41
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.
Upvotes: 4
Views: 8912
Reputation: 54
Your class should be implemented from Serializable for being injectable as a "CDI Bean"
Upvotes: 0
Reputation: 721
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.
Upvotes: 7
Reputation: 156
You need a JavaEE container, and than you need to define Greeting and Test as managed beans. After that you can inject one in another.
Try to take a look at: https://docs.oracle.com/javaee/6/tutorial/doc/girch.html
Upvotes: 0