Reputation: 2681
Hi I have a very simple example. I created a resource in javaee 7 as follows:
@Path("greetings")
public class GreetingsResource {
@Inject
Sample s;
@GET
public JsonObject greetings(){
return Json.createObjectBuilder().add("first","1")
.add("second","2")
.add("third","3")
.add("fourth","4")
.add("helloworld", s.helloWorld())
.build();
}
}
Sample is the following simple EJB:
@Stateless
public class Sample {
public String helloWorld(){
return "Hello World";
}
}
Finally the resource Application class:
@ApplicationPath("resources")
public class RestConfiguration extends Application {
}
I can access the URL: "localhost:8081/jasonandjaxrs/resources/greetings"
The problem is that @Inject gives the following error:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=sample,parent=GreetingsResource,qualifiers={}),position=-1,optional=false
But @EJB seems to work. I am trying to understand why @Inject does not work? Thank you.
Upvotes: 2
Views: 2942
Reputation: 13857
You can't use CDI (means @Inject
) with this setup. CDI only works with beans managed by the container which is not the case for JAX-RS resource classes (your GreetingsResource
).
JAX-RS 2.0 does not support injection of EJBs into JAX-RS components (providers, resources).
If you use @Inject
in your case the injection is provided by the HK2 dependency injection framework which isn't aware of normal CDI beans. It even shouldn't work if you use @EJB
, I don't know why it works, maybe this has to do with Java EE 7.
As it works for you there should be no problem in using @EJB
here, but there are also some alternative approaches in my response to this question.
See also:
Upvotes: 4