This guide explains how to inject Pouch scopes into Jersey 2 resources and vice-versa (inject Jersey types into Pouch scopes).
Example:
JvmScope: values specific to the current JVM
TransactionScope: values specific to a database transaction
HttpScope: values specific to an HTTP request
Example:
MainJvmScope: JvmScope for production
TestJvmScope: JvmScope for tests
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).
@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();
}
}
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());
}
}
}
The code repository contains a working example. Download a copy and try it for yourself.
Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0