2

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.

U-L
  • 2,671
  • 8
  • 35
  • 50

1 Answers1

4

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:

Community
  • 1
  • 1
unwichtich
  • 13,712
  • 4
  • 53
  • 66
  • Thank you @unwichtich. I added stateless to the resource and that at first gave me an error "JAX-RS EJB integration can not be supported". It worked after restarting the server. I am just trying different things. Is there a good tutorial on the different annotations in java ee? Thank you. – U-L May 03 '14 at 23:15
  • There are mainly technical reference docs about all the annotations but I think this is a good list of examples: http://tomee.apache.org/java-ee-6-annotation-examples.html – unwichtich May 04 '14 at 00:38