是否可以使用没有DI容器的Jersey?

时间:2019-05-01 16:35:08

标签: java-ee dependency-injection jersey jersey-2.0

我需要在SE环境中使用没有CDI容器的Jersey 2.28(带有Jetty)。我所有的设置都在web.xml中:

<servlet>
    <servlet-name>JerseyServlet</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.noname.rest</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>JerseyServlet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

这些是我使用的依赖项:

javax.ws.rs-api-2.1.1.jar
javax.activation-1.2.0.jar
jersey-container-jetty-http-2.28.jar
jersey-container-servlet-core-2.28.jar
jersey-server-2.28.jar
jersey-common-2.28.jar
cdi-api-2.0.jar
javax.inject-2.5.0-b62.jar

这是我的资源

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("myresource")
public class MyResource {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getIt() {
        return "Got it!";
    }
}

这就是我得到的:

java.lang.IllegalStateException: InjectionManagerFactory not found.
    at org.glassfish.jersey.internal.inject.Injections.lambda$lookupInjectionManagerFactory$0(Injections.java:74) ~[jersey-common-2.28.jar:?]
    at java.util.Optional.orElseThrow(Optional.java:408) ~[?:?]
    at org.glassfish.jersey.internal.inject.Injections.lookupInjectionManagerFactory(Injections.java:74) ~[jersey-common-2.28.jar:?]
    at org.glassfish.jersey.internal.inject.Injections.createInjectionManager(Injections.java:69) ~[jersey-common-2.28.jar:?]
    at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:258) ~[jersey-server-2.28.jar:?]
    at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:311) ~[jersey-container-servlet-core-2.28.jar:?]
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:154) ~[jersey-container-servlet-core-2.28.jar:?]
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:346) ~[jersey-container-servlet-core-2.28.jar:?]
    at javax.servlet.GenericServlet.init(GenericServlet.java:244) ~[javax.servlet-api-and-schemas-3.1.0.jar:?]
    at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:672) [jetty-servlet-9.4.14.v20181114.jar:?]
    at org.eclipse.jetty.servlet.ServletHolder.initialize(ServletHolder.java:429) [jetty-servlet-9.4.14.v20181114.jar:?]
    at org.eclipse.jetty.servlet.ServletHandler.lambda$initialize$0(ServletHandler.java:750) [jetty-servlet-9.4.14.v20181114.jar:?]

我知道Jersey可以与其他DI容器一起使用,例如Weld,HK2等。但是,没有DI容器也可以使用它吗?如果是,那怎么办?

1 个答案:

答案 0 :(得分:2)

否,不可能。泽西岛的依赖项注入提供者只有一个SPI。它需要实现才能运行。像JAX-RS一样,只是一个规范,但是它需要一个实现(例如Jersey或RESTEasy)才能运行。这是完全一样的。 Jersey在内部使用了大量依赖注入,因此核心代码在其代码库中使用门面进行DI。并且我们需要提供基础实现以使其运行。如您所了解,当前可用的实现是HK2和CDI(jersey-hk2jersey-cdi2-se)。我确定您已经看过this post