2013-07-23 45 views
2

我到處搜索了一個關於如何在Jersey 2.0中使用HK2依賴注入的基本示例,但總結得不多。你如何在Jersey 2.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"); 

任何幫助將不勝感激。

回答

4

原來我只是需要添加幾行代碼,但我會在這裏發佈它以防其他人有同樣的問題。

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/Jersey 2.0推出更多的例子!

+0

感謝您的信息!你見過這個https://github.com/jersey/jersey/pull/15(它增加了對澤西島的支持) –

+1

太棒了!我得看看這個。我對hk2感到有些沮喪。 –