简体   繁体   English

您如何在Jersey 2.0中使用HK2依赖项注入?

[英]How do you use HK2 dependency injection with Jersey 2.0?

I have searched everywhere for a basic example of how to use HK2 dependency injection in Jersey 2.0, but have come up short. 我到处搜索了有关如何在Jersey 2.0中使用HK2依赖项注入的基本示例,但没有简短介绍。

From this question , it appears you need to create a class which extends AbstractBinder . 这个问题看来,您需要创建一个扩展AbstractBinder的类。 However, the rest of the example shows how to register the binder with your application by editing the web.xml file. 但是,该示例的其余部分显示了如何通过编辑web.xml文件向应用程序注册活页夹。 However, I want to avoid this and would like to instead register the binder with my HttpServer instance directly. 但是,我想避免这种情况,而是想直接在我的HttpServer实例中注册活页夹。

This is what I have written for my 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");

Any help will be greatly appreciated. 任何帮助将不胜感激。

Turns out I just needed to add a couple of lines of code, but I'll post it here in case anyone else has the same problem. 原来,我只需要添加几行代码,但是如果有人遇到相同的问题,我将在此处发布。

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, "/");

The ResourceConfig lets you tell the server where to find your dynamic resources, in my case "com.danny.resources". ResourceConfig允许您告诉服务器在哪里可以找到动态资源,在我的例子中是“ com.danny.resources”。 It also allows you to register hk2 binders which will be used to inject those resources into your code. 它还允许您注册hk2活页夹,该活页夹将用于将那些资源注入代码中。

Hope this helps someone along the way, and I hope hk2/Jersey 2.0 puts out some more examples! 希望这能对整个过程有所帮助,我希望hk2 / Jersey 2.0能够提供更多示例!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM