Clone wiki

pouch-jersey2 / Home


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


ApplicationScope: Values bound to an application run.

TransactionScope: Values bound to a database transaction.

HttpScope: Values bound to an HTTP request.

Step 2: Implement scopes


MainApplicationScope: ApplicationScope for production

TestApplicationScope: ApplicationScope for unit 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

public final class HelloWorldResource
    public HelloWorldResource(HttpScope scope)
        this.scope = scope;

    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
    public void test1() throws SQLException
        try (ApplicationScope applicationScope = new TestApplicationScope();
            TransactionScope transaction = applicationScope.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.


Licensed under the Apache License, Version 2.0: