我最終使用了Google Guice,它是一個輕量級的DI框架,可以很好地與澤西島集成。這是我必須做的:
首先,我加在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);
}
});
}
}
我用碼頭,而不是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
來自於給出了一個答案陽光格里森的示例代碼:https://stackoverflow.com/a/3296467 - 我本來
root.addServlet(new ServletHolder(new ServletContainer(new PackagesResourceConfig("com.example.resource"))), "/*");
的替代線路
root.addServlet(EmptyServlet.class, "/*");
但是,這導致澤西試圖執行依賴注入而不是Guice,從而導致運行時錯誤。
http://jersey.java.net/documentation/latest/migration.html#mig-server-inject-custom-objects – tuxSlayer