Discussion:
Question about hk2 interceptors
(too old to reply)
Diogo Guerra
2014-09-21 15:31:01 UTC
Permalink
Hi Everyone,

I had to upgrade my jersey-guice project from 1.17 to the latest 2.12
version.

In fact we were not using any special injection from Guice, only
interception to do authorization and logging.

However what we had was intercepting all the methods of classes of our
resources with the following code in our Guice Module:

bindInterceptor(Matchers.inSubpackage("com.company.web.resources"),
Matchers.any(), new TracingInterceptor());

With jersey 2 and the new dependency injection system, I couldn’t get the
guice incterceptors working. It seems that the hk2-guice
<https://hk2.java.net/2.3.0/guice-bridge.html> bridge is only to injection
not to interception.

Then I started to look at the code needed for interception with hk2.

I got to this point:

An interception service:

public class MyInterceptionService implements InterceptionService {

private static List<MethodInterceptor> trace = Arrays.asList(new
TracingInterceptor());
private static String targetPackageName = "com.company.web.resources";

@Override

public Filter getDescriptorFilter() {
return BuilderHelper.allFilter();
}

@Override
public List<MethodInterceptor> getMethodInterceptors(Method method) {
if (method.isSynthetic()) {
return null;
}

String classPackageName =
method.getDeclaringClass().getPackage().getName();
if (!classPackageName.equals(targetPackageName)
&& !classPackageName.startsWith(targetPackageName + ".")) {
return null;
}

return trace;
}

@Override
public List<ConstructorInterceptor>
getConstructorInterceptors(Constructor<?> constructor) {
return null;
}

Bind the interception service

register(new AbstractBinder() {
@Override
protected void configure() {

bind(MyInterceptionService.class).to(InterceptionService.class).in(Singleton.class);
}
});

However I have two questions:

It seems that it is not possible to bind an instance of an
InterceptionService but only the class. How can we configure an
InterceptionService? In this case, how can we pass the package name to
MyInterceptionService? Otherwise Ii will have to write a new class for each
of my web applications to use my TracingInterceptor?
Is there any simpler way to do this? With guice set up an Interceptor with
1 linee of code, with HK2 I need 30+ lines of code and I can’t reuse the
code.

Thanks,

—Diogo
​

Loading...