Skip to content

Latest commit

 

History

History
88 lines (65 loc) · 2.72 KB

README.md

File metadata and controls

88 lines (65 loc) · 2.72 KB

Introduction

This guide explains how to inject Pouch scopes into Jersey 2 resources and vice-versa (inject Jersey types into Pouch scopes).

Step 1: Define scope interfaces

Example:

JvmScope: values specific to the current JVM

TransactionScope: values specific to a database transaction

HttpScope: values specific to an HTTP request

Step 2: Implement scopes

Example:

MainJvmScope: JvmScope for production

TestJvmScope: JvmScope for tests

Step 3: Integrate Pouch with Jersey

HK2 is Jersey's internal dependency-injection mechanism. HK2 Binders are equivalent to Guice Modules or Spring @Configuration

First, you'll need to implement an HK2 Binder ( e.g. MainPouchBinder), then you'll need to register the Binder with Jersey (e.g. MainApplication).

Step 4: Inject scopes into Jersey resources

@Path("helloworld")
public final class HelloWorldResource
{
  @Inject
  public HelloWorldResource(HttpScope scope)
  {
    this.scope = scope;
  }

  @GET
  @Produces("text/plain")
  public String getHello()
  {
    return "Hello world!\n" +
      "HTTP-scoped value       : " + scope.getRequestedUri() + "\n" +
      "Application-scoped value: " + scope.getMode();
  }
}

Step 5: Inject scopes into unit tests

public final class TestDatabase
{
  @Test
  public void test1()
  {
    try (JvmScope jvmScope = new TestJvmScope();
         TransactionScope transaction = jvmScope.createTransactionScope())
    {
      Connection connection = transaction.getConnection();
      System.out.println("test1() running against " + connection.getMetaData().getURL());
    }
  }
}

Try it!

The code repository contains a working example. Download a copy and try it for yourself.

License

Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0