问题

从头开始没有任何以前的Jersey 1.x知识,我很难理解如何在我的Jersey 2.0项目中设置依赖注入。

我也明白HK2可用于Jersey 2.0,但我似乎无法找到有助于Jersey 2.0集成的文档。

@ManagedBean
@Path("myresource")
public class MyResource {

    @Inject
    MyService myService;

    /**
     * Method handling HTTP GET requests. The returned object will be sent
     * to the client as "text/plain" media type.
     *
     * @return String that will be returned as a text/plain response.
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/getit")
    public String getIt() {
        return "Got it {" + myService + "}";
    }
}

@Resource
@ManagedBean
public class MyService {
    void serviceCall() {
        System.out.print("Service calls");
    }
}

的pom.xml

<properties>
    <jersey.version>2.0-rc1</jersey.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey</groupId>
            <artifactId>jersey-bom</artifactId>
            <version>${jersey.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-common</artifactId>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey</groupId>
        <artifactId>jax-rs-ri</artifactId>
    </dependency>
</dependencies>

我可以让容器启动并提供我的资源,但是只要我将@Inject添加到MyService,框架就会抛出异常:

SEVERE: Servlet.service() for servlet [com.noip.MyApplication] in context with path [/jaxrs] threw exception [A MultiException has 3 exceptions.  They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=MyService,parent=MyResource,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,1039471128)
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of com.noip.MyResource errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on com.noip.MyResource
] with root cause
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=MyService,parent=MyResource,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,1039471128)
    at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:74)

我的初学者项目可在GitHub获得:https://github.com/donaldjarmstrong/jaxrs


#1 热门回答(92 赞)

你需要定义一个AbstractBinder并在JAX-RS应用程序中注册它。绑定器指定依赖注入应如何创建类。

public class MyApplicationBinder extends AbstractBinder {
    @Override
    protected void configure() {
        bind(MyService.class).to(MyService.class);
    }
}

在类型为MyService.class的参数或字段上检测到@Inject时,使用classMyService进行实例化。要使用此绑定器,需要在JAX-RS应用程序中注册。在yourweb.xml中,定义一个这样的JAX-RS应用程序:

<servlet>
  <servlet-name>MyApplication</servlet-name>
  <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
  <init-param>
    <param-name>javax.ws.rs.Application</param-name>
    <param-value>com.mypackage.MyApplication</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>MyApplication</servlet-name>
  <url-pattern>/*</url-pattern>
</servlet-mapping>

实现MyApplicationclass(在init-param中指定)。

public class MyApplication extends ResourceConfig {
    public MyApplication() {
        register(new MyApplicationBinder());
        packages(true, "com.mypackage.rest");
    }
}

指定依赖项注入的绑定程序在类的构造函数中注册,我们还使用packages()方法调用告诉应用程序在何处查找REST资源(在你的情况下,MyResource)。


#2 热门回答(44 赞)

首先只是回答接受答案中的评论。

"绑定做什么?如果我有接口和实现怎么办?"

它简单地读取bind( implementation ).to( contract )。你可以选择chain.in( scope )。默认范围为PerLookup。所以,如果你想要一个单例,你可以

bind( implementation ).to( contract ).in( Singleton.class );

还有aRequestScoped可用

此外,你还可以使用bind(Instance).to(Class)代替4331202501,它将自动成为单例。

加入到accepted answer

对于那些试图弄清楚如何在你的web.xml中注册你的AbstractBinder实现的人(即你没有使用aResourceConfig),似乎不会通过包扫描发现活页夹,即

<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
    <param-name>jersey.config.server.provider.packages</param-name>
    <param-value>
        your.packages.to.scan
    </param-value>
</init-param>

或者这个

<init-param>
    <param-name>jersey.config.server.provider.classnames</param-name>
    <param-value>
        com.foo.YourBinderImpl
    </param-value>
</init-param>

为了让它工作,我必须实现aFeature

import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.ext.Provider;

@Provider
public class Hk2Feature implements Feature {

    @Override
    public boolean configure(FeatureContext context) {
        context.register(new AppBinder());
        return true;
    }
}

@Provider注释应该允许Feature被包扫描拾取。或者,如果没有包扫描,你可以在web.xml中明确注册Feature

<servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>
            com.foo.Hk2Feature
        </param-value>
    </init-param>
    ...
    <load-on-startup>1</load-on-startup>
</servlet>

另请参见:-使用Jersey的自定义方法参数注入

  • 如何将对象注入泽西请求上下文?
  • 如何在jersey / hk2应用程序中正确配置EntityManager?
  • 请求将单一注射注入单例

以及来自Jersey文档的一般信息

  • 自定义注入和生命周期管理

##更新

###工厂

除了已接受答案中的基本绑定外,你还拥有工厂,你可以在其中拥有更复杂的创建逻辑,还可以访问请求上下文信息。例如

public class MyServiceFactory implements Factory<MyService> {
    @Context
    private HttpHeaders headers;

    @Override
    public MyService provide() {
        return new MyService(headers.getHeaderString("X-Header"));
    }

    @Override
    public void dispose(MyService service) { /* noop */ }
}

register(new AbstractBinder() {
    @Override
    public void configure() {
        bindFactory(MyServiceFactory.class).to(MyService.class)
                .in(RequestScoped.class);
    }
});

然后你可以将MyService注入你的资源类。


#3 热门回答(11 赞)

选定的答案可以追溯到前一段时间。在自定义HK2活页夹中声明每个绑定是不切实际的。我正在使用Tomcat,我只需添加一个依赖项。尽管它是专为Glassfish设计的,但它完全适合其他容器。

<dependency>
        <groupId>org.glassfish.jersey.containers.glassfish</groupId>
        <artifactId>jersey-gf-cdi</artifactId>
        <version>${jersey.version}</version>
    </dependency>

确保你的容器也已正确配置(see the documentation)。


原文链接