我在任何地方都搜索了一个如何在Jersey2.0中使用HK2依赖项注入的基本示例,但是还不够。
在this question中,您似乎需要创建一个扩展AbstractBinder的类。但是,该示例的其余部分展示了如何通过编辑web.xml文件向应用程序注册绑定器。但是,我希望避免这种情况,并希望直接将绑定器注册到我的HttpServer实例中。
这就是我为我的HttpServer所写的:
int port = config.getInt("port", 8080);
boolean useFake = config.getBoolean("fake", false);
final URI baseUri = URI.create("http://" + "localhost" + ":" + port + "/");
List<Binder> binders = Arrays.asList((Binder)new StatusModule(useFake),
(Binder)new NetworkModule(useFake));
final ApplicationHandler applicationHandler = new ApplicationHandler();
applicationHandler.registerAdditionalBinders(binders);
WebappContext webappContext = new WebappContext("Webapp context", "/resources");
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(
baseUri, applicationHandler);
for(NetworkListener listener : server.getListeners()){
listener.setCompression("on");
}
server.getServerConfiguration().addHttpHandler(
new StaticHttpHandler("/jersey2app/www"), "/static");任何帮助都将不胜感激。
发布于 2013-07-24 14:23:28
结果,我只需要添加几行代码,但我会在这里发布,以防其他人遇到同样的问题。
ResourceConfig rc = new ResourceConfig();
rc.packages("com.danny.resources");
rc.registerInstances(new StatusModule(useFake), new NetworkModule(useFake));
GrizzlyHttpContainer resourceConfigContainer = ContainerFactory
.createContainer(GrizzlyHttpContainer.class, rc);
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri);
server.getServerConfiguration().addHttpHandler(resourceConfigContainer, "/");ResourceConfig允许您告诉服务器在哪里找到您的动态资源,在我的例子中是"com.danny.resources“。它还允许您注册hk2绑定程序,用于将这些资源注入到代码中。
希望这能帮到别人,我希望HK2/泽西岛2.0提供更多的例子!
https://stackoverflow.com/questions/17814517
复制相似问题