Jersey 2.0でguice-servletを使用する方法を示すサンプルコードはありますか?
8 に答える
これは、Jersey 2 と Guice を接続する最小限の動作 PoC です。
GWizardには、Jersey2 と Guice をすぐに統合できるモジュールが含まれています。完全な JAX-RS サービスの例を次に示します。
public class Main {
@Path("/hello")
public static class HelloResource {
@GET
public String hello() {
return "hello, world";
}
}
public static class MyModule extends AbstractModule {
@Override
protected void configure() {
bind(HelloResource.class);
}
}
public static void main(String[] args) throws Exception {
Guice.createInjector(new MyModule(), new JerseyModule()).getInstance(WebServer.class).startJoin();
}
}
これは、 Squarespace jersey2-guice アダプターに基づいていることに注意してください。これは、Jersey の将来のポイント リリースでは正しく機能しない可能性があります。GWizard は、推奨される RESTEasy JAX-RS モジュールも提供します。
これに関するブログエントリが役立つかもしれません: http://blorn.com/post/107397841765/guice-and-jersey-2-the-easy-way
私はすでにこのサンプルで行っています:
https://github.com/jbescos/tododev
クラスhttps://github.com/jbescos/tododev/blob/master/jersey2-guice/src/main/java/es/tododev/rest/ApplyGuiceContextFilter.javaを ResourceConfig に登録し、guice インジェクターをバインドする必要があります。 AbstractModule で。
@Provider
@PreMatching
public class ApplyGuiceContextFilter implements ContainerRequestFilter, ContainerResponseFilter {
@Inject
public ApplyGuiceContextFilter(ServiceLocator serviceLocator, Injector injector) {
GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
guiceBridge.bridgeGuiceInjector(injector);
}
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
}
@Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext) throws IOException {}
}
これは次のResouceConfig
とおりです。
public class RestConfig extends ResourceConfig {
@Inject
public RestConfig() {
this(Guice.createInjector(new Module(){
@Override
public void configure(Binder arg0) {
// TODO Auto-generated method stub
}
}));
}
// Test
public RestConfig(Injector injector) {
packages(ResourceSample.class.getPackage().getName());
register(ApplyGuiceContextFilter.class);
register(new LoggingFilter(Logger.getLogger(LoggingFilter.class.getName()), true));
property(ServerProperties.TRACING, "ALL");
register(new RestBinder(injector));
}
private static class RestBinder extends AbstractBinder{
private final Injector injector;
private RestBinder(Injector injector){
this.injector = injector;
}
@Override
protected void configure() {
bind(injector).to(Injector.class);
}
}
}
これは組み込み Jetty を使用した例です (おそらく Jetty サーバーでも機能するはずです)。
jetty-jersey-HK2-Guice-ボイラープレート
アプリケーションにGuiceを使用する予定がある場合は、Jersey に注入されたすべての Guice コンポーネントを Guice 構成でバインディングとして宣言する必要があります。
Guice 構成ですべてのバインディングを宣言したくない場合は、ここにアダプターがあります。