泽西岛的依赖注入

时间:2012-05-23 23:56:25

标签: java java-ee dependency-injection jersey

如果我使用Jersey 1.12,并且我有多个资源类,并且他们都需要访问一些共享上下文,那么注入依赖项的最佳方法是什么,无论是在资源类的构造函数中,还是在处理方法?我是否需要使用外部DI库,或者Jersey内置了什么?

即。也许Foos的资源看起来像这样:

package com.example.resource;

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

@Path("/some/api/path/foo")
public class FooResource
{
    @GET
    @Produces("text/html")
    public String getFoo(@QueryParam("id") String id)
    {
        Foo foo = /* get a Foo from some shared context based on id */
        /* Process foo into a String */
    }
}

和吧:

package com.example.resource;

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

@Path("/some/api/path/bar")
public class BarResource
{
    @GET
    @Produces("text/html")
    public String getBar(@QueryParam("id") String id)
    {
        Bar bar = /* get a Bar from some shared context based on id */
        /* Process bar into a String */
    }
}

4 个答案:

答案 0 :(得分:12)

我最终使用了Google Guice,这是一个轻量级的DI框架,可与Jersey完美整合。这就是我必须做的事情:

首先,我在pom.xml中添加了依赖项:

    <dependency>
        <groupId>com.google.inject</groupId>
        <artifactId>guice</artifactId>
        <version>3.0</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey.contribs</groupId>
        <artifactId>jersey-guice</artifactId>
        <version>1.12</version>
        <scope>compile</scope>
    </dependency>

我希望将DAO实现为具有接口的单例:

public interface MySingletonDao
{
    // ... methods go here ...
}

和具体实施:

@Singleton
public class ConcreteMySingletonDao implements MySingletonDao
{
    // ... methods go here ...
}

像这样装饰资源类:

@Path("/some/path")
@RequestScoped
public class MyResource
{
    private final MySingletonDao mySingletonDao;

    @Inject
    public MyResource(MySingletonDao mySingletonDao)
    {
        this.mySingletonDao = mySingletonDao;
    }

    @POST
    @Produces("application/json")
    public String post() throws Exception
    {
            // ... implementation goes here ...
    }
}

创建了一个将执行绑定的类:

public class GuiceConfig extends GuiceServletContextListener
{
    @Override
    protected Injector getInjector()
    {
        return Guice.createInjector(new JerseyServletModule()
        {
            @Override
            protected void configureServlets()
            {
                bind(MyResource.class);
                bind(AnotherResource.class);
                bind(MySingletonDao.class).to(ConcreteMySingletonDao.class);
                serve("/*").with(GuiceContainer.class);
            }
        });
    }
}

我使用Jetty而不是Glassfish来实际充当服务器。在我的功能测试中,它看起来像:

private void startServer() throws Exception
{
    this.server = new Server(8080);
    ServletContextHandler root =
        new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);

    root.addEventListener(new GuiceConfig());
    root.addFilter(GuiceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    root.addServlet(EmptyServlet.class, "/*");

    this.server.start();
}

EmptyServlet来自Sunny Gleason的示例代码,作为答案给出:https://stackoverflow.com/a/3296467 - 我最初有

root.addServlet(new ServletHolder(new ServletContainer(new PackagesResourceConfig("com.example.resource"))), "/*");

而不是

root.addServlet(EmptyServlet.class, "/*");

但是这导致Jersey尝试执行依赖注入而不是Guice,这会导致运行时错误。

答案 1 :(得分:3)

您可以使用SingletonTypeInjectableProvider:http://jersey.java.net/nonav/apidocs/1.12/jersey/com/sun/jersey/spi/inject/SingletonTypeInjectableProvider.html

示例:

ResourceConfig resourceConfig = new DefaultResourceConfig();
resourceConfig.getSingletons().add(
        new SingletonTypeInjectableProvider<Context, SingletonType>(
               SingletonType.class, new SingletonType()) {});{code}

或者您可以创建SingletonTypeInjectableProvider后代,使用@Provider对其进行注释将其添加为类。您可以在任何需要的地方注入提供的实例,以及标准的泽西注射开始的地方。

答案 2 :(得分:1)

有一个支持Spring依赖注入的jersey-spring项目。用SpringServlet替换你的球衣ServletContainer,在你的web.xml中添加一个ContextLoaderListener,你可以将bean注入你的组件。这是一个相当不错的设置演练

http://www.mkyong.com/webservices/jax-rs/jersey-spring-integration-example/

修改

这是一个不需要添加任何依赖项的想法。创建自己的ServletContextListener,将对象添加到ServletContext。然后将ServletContext注入资源

public class MyContextListener implements ServletContextListener
{

    @Override
    public void contextDestroyed(ServletContextEvent event)
    {
    }

    @Override
    public void contextInitialized(ServletContextEvent event)
    {
        ServletContext context = event.getServletContext();
        context.setAttribute(Foo.class.getName(), new FooImpl());
    }

}

然后在你的资源

@Path("blah")
public class MyResource 
{
   private Foo foo;

   public MyResource(@Context ServletContext context)
   {
      foo = (Foo) context.getAttribute(Foo.class.getName());
   } 
}

答案 3 :(得分:1)

除非您愿意,否则不必使用外部库。有充分证据表明,让CDI与泽西岛正常合作目前是一件痛苦的事。但是,我可以从经验中说,可以自己完成它。自从我跳过这些篮球以来,已经有一段时间了,但我似乎记得我们必须让我们的资源无状态EJB才能让它发挥作用。我可能已经采取了其他措施,但我现在不记得了。

当Jersey 2.0出现时,这应该会变得更加容易,因为他们将切换到使用Core CDI实现而不是他们自己的实现。有关详细信息,请参阅此错误:

http://java.net/jira/browse/JERSEY-517