我最后使用Google Guice(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);
}
});
}
}
我用Jetty而不是玻璃鱼来充当服务器。在我的功能测试中,这看起来像:
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, "/*");
但这使得泽西岛尝试和进行 依赖性注射 而不是Guice, 这导致了运行时间错误。