我可以使用CDI在Jersey

我可以使用CDI在Jersey

本文介绍了我可以使用CDI在Jersey 1.x中@Inject一个类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我问的是这个问题,但针对Jersey 1.x:依赖注入使用Jersey 2.0

I think I'm asking this question but for Jersey 1.x: Dependency injection with Jersey 2.0

我正在使用Glassfish 3,CDI和Jersey1.x.我有一个@WebService,它正在注入这样的类:

I'm using Glassfish 3, CDI and Jersey 1.x. I have a @WebService that is injecting a class like this:

@Inject
Foo foo;

我已经在@WebService中对其进行了测试,并且可以正常工作.但是,当我尝试使用foo时,Jersey资源中的同一行代码会引发NPE.我认为Jersey 1.x忽略了CDI批注.我如何才能像在@WebService中那样进行依赖项注入?

I've tested this in the @WebService and it works. But the same line of code in my Jersey resource throws a NPE when it tries to use foo. I think Jersey 1.x is ignoring the CDI annotations. How can I get dependency injection working like it does in my @WebService?

Foo是一个pojo,而我的web.xml使用的是ServletContainer:

Foo is a pojo and my web.xml is using the ServletContainer:

<servlet>
    <servlet-name>JerseyServlet</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>


我在这里找到了一些帮助.问题是我的Foo @Inject拥有自己的bean(它们实际上是EJB,它们来自其中包含@Provides的类). resourceContext.getResource(Foo.class);返回Foo的实例,但是foo@Inject ed字段为空.


I've found some help here. The problem is my Foo @Injects its own beans (they're actually EJBs that come from a class with @Provides in it). resourceContext.getResource(Foo.class); returns an instance of Foo, but foo's @Injected fields are null.

推荐答案

我发现一篇文章,其中介绍了如何执行此操作:

I found an article that explains how to do this:

  1. 让CDI实例化依赖关系,但让Jersey管理它 可以使用@ManagedBean和特定于Jersey的注释来实现.
  2. 让CDI实例化依赖关系,然后让CDI管理它. 可以使用@RequestScoped或其他CDI特定注释来实现.
  1. Let CDI instantiate the dependency, but let Jersey managed it This can be achived using @ManagedBean and a Jersey specific annotation.
  2. Let CDI instantiate the dependency and let CDI manage it. This can be achieved using @RequestScoped or other CDI specific annotations.

我选择了第一个选项,并将javax.annotation.ManagedBean注释放在我的资源上. 这里是一个例子:

I chose the first option and put the javax.annotation.ManagedBean annotation on my resource. Here's an example:

package com.coderskitchen.thegreeter.rest;

import com.coderskitchen.thegreeter.greetings.GreetingService;

import javax.annotation.ManagedBean;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

@Path("/greet")
@ManagedBean
public class Greeter {
    @Inject
    GreetingService gs;
    @GET
    @Path("{name}")
    public String greetSomeone(@PathParam("name") String name) {
        return gs.greetSomeone(name);
    }
}

*我也发现了这篇官方文章,实际上并没有什么用: http://docs.oracle.com/javaee/7/tutorial/doc/jaxrs-advanced004.htm

* Also I found this official article, which actually isn't as useful: http://docs.oracle.com/javaee/7/tutorial/doc/jaxrs-advanced004.htm

这篇关于我可以使用CDI在Jersey 1.x中@Inject一个类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 20:03