Wiki

Clone wiki

pouch-jersey1 / Home

Introduction

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

Step 1: Define scope interfaces

Example:

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

Example:

MainApplicationScope: ApplicationScope for production

TestApplicationScope: ApplicationScope for unit tests

Step 3: Integrate Pouch with Jersey

First, you'll need to implement an IoCComponentProviderFactory (e.g. PouchInjector), then you'll need to register the factory with a ServletContainer (e.g. PouchContainer).

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() 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.

License

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

Updated