Cant inject Bean class into Restfull WebService (JAX-RS) [duplicate]

自作多情 提交于 2019-12-06 14:10:20
Carlo Pellegrini

The @EJB annotation is not supposed to work for all objects.

For this to work you need to use CDI, so substitute the @EJB with @Inject and your bean will be correctly injected.

See also: Inject an EJB into JAX-RS (RESTful service)

EDIT:

Also be sure to add beans.xml to every jar/war archive containing classes you want to inject or be injected. It goes into META-INF for jars and WEB-INF for wars.

Your REST application class packaget.Rest should extend javax.ws.rs.core.Application as in:

@ApplicationPath("/root-path") 
public class Rest extends Application 
{ 
}

And according to the documentation here on JBoss 6.1 REST and CDI should work out of the box. If you specify the org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher and the org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap you are probably messing up the RestEasy/CDI classloading.

So your web.xml should look as:

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee java.sun.com/xml/ns/javaee/…"> 
</web-app> 

Anyway, I pushed a working example on github

Roland

You should add /src/main/resources/META-INF/beans.xml. This will enable injection.

I has similar issue, for me the problem was creating my RESTful bean on my own with constructor, which was dumb while using EJBs and @EJB injection:

PROBLEM:

@ApplicationPath("/")
public class RestApplication extends Application {
    private Set<Object> singletons = new HashSet<Object>();
    public RestApplication() {
        singletons.add(new RestService());
    }
    @Override
    public Set<Object> getSingletons() {
        return singletons;
    }
}

SOLUTION:

@ApplicationPath("/")
public class RestApplication extends Application {
}

Hope it might save sb's time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!