user2966560
user2966560

Reputation: 379

Why CDI not working?

I have the next rest service:

@ApplicationPath("geo")
@Path("weather")
public class MainResource extends Application {

    @Inject
    private MainDep dep;

    @GET
    public String printGotIt() {
        return "Got it!";
    }

    @GET
    @Path("propaganda")
    public String printPropaganda() {
        return dep.printPropaganda();
    }
}

MainDep dependency code:

public class MainDep {
    public String printPropaganda() {
        return "Interesting enterprise";
    }
}

When I trying to use resource on following url: host:port/root/geo/weather GlassFish threw a javax.servlet.ServletException:

type Exception report

messageInternal Server Error

descriptionThe server encountered an internal error that prevented it from fulfilling this request.
exception
`javax.servlet.ServletException: Servlet.init() for servlet com.app.weather.rs.MainResource threw exception
root cause`
A MultiException has 1 exceptions.  They are:
    1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=MainDep,parent=MainResource,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,22064320)
    root cause
    org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=MainDep,parent=MainResource,qualifiers={}),position=-1,optional=false

Upvotes: 0

Views: 1675

Answers (2)

Michal Gajdos
Michal Gajdos

Reputation: 10379

The problem here is that you're mixing JAX-RS Application + JAX-RS resource class in one class and on top of that you're adding a CDI injection into the mix.

Try to separate the JAX-RS Application from JAX-RS resource, like:

@ApplicationPath("geo")
public class MainApplication extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        final Set<Class<?>> classes = new HashSet<Class<?>>();
        classes.add(MainResource.class);
        return classes;
    }
}

and

@Path("weather")
public class MainResource {

    @Inject
    private MainDep dep;

    @GET
    public String printGotIt() {
        return "Got it!";
    }

    @GET
    @Path("propaganda")
    public String printPropaganda() {
        return dep.printPropaganda();
    }
}

Upvotes: 1

John Ament
John Ament

Reputation: 11723

You need to add @RequestScoped to your class.

Upvotes: 1

Related Questions