注入Jersey资源类

时间:2011-11-02 18:11:35

标签: java jersey inject

我确实尝试过以下链接 How to wire in a collaborator into a Jersey resource?Access external objects in Jersey Resource class 但我仍然无法找到一个显示如何注入Resource类的工作示例。 我没有使用Spring或Web容器。

我的资源

package resource;

import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/something")
public class Resource
{
    @MyResource
    Integer foo = null;
    private static String response = "SampleData from Resource";

    public Resource()
    {
        System.out.println("...constructor called :" + foo);
    }

    @Path("/that")
    @GET
    @Produces("text/plain")
    public String sendResponse()
    {
        return response + "\n";
    }
}

我的提供商

package resource;

import javax.ws.rs.ext.Provider;
import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.core.spi.component.ComponentScope;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.InjectableProvider;

@Provider
public class MyResourceProvider implements InjectableProvider<MyResource, Integer>
{
    @Override
    public ComponentScope getScope()
    {
       return ComponentScope.PerRequest;
    }

     @Override
    public Injectable getInjectable(final ComponentContext arg0, final MyResource arg1, final Integer arg2)
    {
       return new Injectable<Object>()
        {
            @Override
            public Object getValue()
            {
              return new Integer(99);
            }
        };
    }
}

我的EndpointPublisher

import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory;

class EndpointPublisher
{
    public static void main(final String[] args)
    {

        final String address = "http://localhost:8080/";
        final Map<String, String> config = new HashMap<String, String>();
        config.put("com.sun.jersey.config.property.packages", "resource");
        try
        {
            GrizzlyWebContainerFactory.create(address, config);
            System.out.println("server started ....." + address);
            callGet();
        }
        catch (final Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void callGet()
    {
        Client client = null;
        ClientResponse response = null;
        client = Client.create();
        final WebResource resource =
                client.resource("http://localhost:8080/something");
        response = resource.path("that")
                .accept(MediaType.TEXT_XML_TYPE, MediaType.APPLICATION_XML_TYPE)
                .type(MediaType.TEXT_XML)
                .get(ClientResponse.class);
        System.out.println(">>>> " + response.getResponseDate());
    }
}

我的注释

@Retention(RetentionPolicy.RUNTIME)
public @interface MyResource
{}

但是当我执行我的EndpointPublisher时,我无法注入foo !!

2 个答案:

答案 0 :(得分:8)

您的InjectableProvider未正确实施。第二个类型参数不应该是您尝试注入的字段的类型 - 而应该是上下文 - java.lang.reflect.Type类或com.sun.jersey.api.model.Parameter类。在您的情况下,您将使用类型。因此,您的InjectableProvider实现应如下所示:

package resource;

import javax.ws.rs.ext.Provider;
import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.core.spi.component.ComponentScope;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.InjectableProvider;
import java.lang.reflect.Type;

@Provider
public class MyResourceProvider implements InjectableProvider<MyResource, Type> {

    @Override
    public ComponentScope getScope() {
        return ComponentScope.PerRequest;
    }

    @Override
    public Injectable getInjectable(final ComponentContext arg0, final MyResource arg1, final Type arg2) {
        if (Integer.class.equals(arg2)) {
            return new Injectable<Integer>() {

                @Override
                public Integer getValue() {
                    return new Integer(99);
                }
            };
        } else {
            return null;
        }
    }
}

每个请求可注入提供程序(PerRequestTypeInjectableProvider)以及单例可注入提供程序(SingletonTypeInjectableProvider)都有一个帮助程序类,因此您可以通过继承它来进一步简化它:

package resource;

import javax.ws.rs.ext.Provider;
import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.PerRequestTypeInjectableProvider;

@Provider
public class MyResourceProvider extends PerRequestTypeInjectableProvider<MyResource, Integer> {
    public MyResourceProvider() {
        super(Integer.class);
    }

    @Override
    public Injectable<Integer> getInjectable(ComponentContext ic, MyResource a) {
        return new Injectable<Integer>() {
            @Override
            public Integer getValue() {
                return new Integer(99);
            }
        };
    }
}

请注意,对于这些辅助类,第二个类型参数是字段的类型。

还有一件事 - 在调用构造函数之后注入发生,因此资源的构造函数仍将打印出...constructor called :null,但如果更改资源方法以返回foo ,你会看到你得到的回复是99。

答案 1 :(得分:2)

此解决方案效果很好,我想分享我发现的在球衣资源上启用CDI的内容。

这是有史以来最简单的bean:

package fr.test;

import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;

@RequestScoped
public class Test {

    private int i;

    @PostConstruct
    public void create() {
        i = 6;
    }

    public int getI() {
        return i;
    }
}

在你的资源类中,我们只是注入这个bean,就像在任何正常的上下文中那样:

package fr.test;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/login")
public class LoginApi {

    @Inject
    private Test test;

    @GET 
    @Produces("text/plain")
    public String getIt() {
        return "Hi there!" + test;
    }
}

这是关键。我们定义了一个Jersey“InjectionProvider”,它负责bean的解析:

package fr.test;

import javax.inject.Inject;

import java.lang.reflect.Type;
import javax.ws.rs.ext.Provider;

import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.core.spi.component.ComponentScope;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.InjectableProvider;

import fr.xxxxxxxxxx.ApplicationBeans;

@Provider
public class InjectionProvider implements InjectableProvider<Inject, Type> {

    public ComponentScope getScope() {
        // CDI will handle scopes for us
        return ComponentScope.Singleton;
    }

    @Override
    public Injectable<?> getInjectable(ComponentContext context,
            Inject injectAnno, Type t) {
        if (!(t instanceof Class))
            throw new RuntimeException("not injecting a class type ?");

        Class<?> clazz = (Class<?>) t;

        final Object instance = ApplicationBeans.get(clazz);

        return new Injectable<Object>() {
            public Object getValue() {
                return instance;
            }
        };
    }
}
使用我们正在处理的注释类型和上下文类型(此处为普通java类型)输入

InjectableProvider

ApplicationBeans只是bean解析的一个简单帮助器。以下是其内容:

package fr.xxxxxxxxxx;

import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.inject.Inject;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import fr.xxxxxxxxxxxxx.UnexpectedException;

/**
 * Gives direct access to managed beans - Designed to be used from unmanaged code
 * 
 * @author lgrignon
 * 
 */
@ApplicationScoped
public class ApplicationBeans
{

  protected static ApplicationBeans instance;

  @Inject
  private BeanManager beanManager;

  /**
   * Gets instance
   * 
   * @return Instance from managed environment
   */
  public static ApplicationBeans instance()
  {
    if (instance == null)
    {
      BeanManager beanManager;
      InitialContext ctx = null;
      try
      {
        ctx = new InitialContext();
        beanManager = (BeanManager)ctx.lookup("java:comp/BeanManager");
      }catch(NamingException e)
      {
        try
        {
          beanManager = (BeanManager)ctx.lookup("java:app/BeanManager");
        }catch(NamingException ne)
        {
          throw new UnexpectedException("Unable to obtain BeanManager.", ne);
        }
      }

      instance = getBeanFromManager(beanManager, ApplicationBeans.class);
    }

    return instance;
  }

  /**
   * Gets bean instance from context
   * 
   * @param <T>
   *          Bean's type
   * @param beanType
   *          Bean's type
   * @param annotations
   *          Bean's annotations
   * @return Bean instance or null if no
   */
  public static <T> T get(final Class<T> beanType, Annotation... annotations)
  {
    return instance().getBean(beanType, annotations);
  }

  /**
   * Gets bean instance from context
   * 
   * @param <T>
   *          Bean's type
   * @param beanType
   *          Bean's type
   * @param annotations
   *          Bean's annotations
   * @return Bean instance or null if no
   */
  public <T> T getBean(final Class<T> beanType, Annotation... annotations)
  {
    return getBeanFromManager(beanManager, beanType, annotations);
  }

  @SuppressWarnings("unchecked")
  private static <T> T getBeanFromManager(BeanManager beanManager, final Class<T> beanType, Annotation... annotations)
  {
    Set<Bean<?>> beans = beanManager.getBeans(beanType, annotations);
    if (beans.size() > 1)
    {
      throw new UnexpectedException("Many bean declarations found for type %s (%s)", beanType.getSimpleName(), beansToString(beans));
    }

    if (beans.isEmpty())
    {
      throw new UnexpectedException("No bean declaration found for type %s", beanType.getSimpleName());
    }

    final Bean<T> bean = (Bean<T>)beans.iterator().next();
    final CreationalContext<T> context = beanManager.createCreationalContext(bean);
    return (T)beanManager.getReference(bean, beanType, context);
  }

  private static String beansToString(Collection<Bean<?>> beans)
  {
    String[] beansLabels = new String[beans.size()];
    int i = 0;
    for (final Bean<?> bean : beans)
    {
      beansLabels[i++] = bean.getName();
    }

    return Arrays.toString(beansLabels);
  }

}

希望这有助于那些想在泽西岛资源中启用CDI注入的人。

再见!