Aop with Guice

Aop has many uses, from doing transaction handling to authorisation. With the powerfull Guice framework it is suprisingly easy.

In this example we mark methods from a class with a Annotiation marker use Guice to intercept them.

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
public @interface InjectedTransaction {

}

Now, we mark a method of some class with it:

public class BasicDummyService {

 @InjectedTransaction
 public void testService() {
 System.out.println("doing testService");
 }
}

Now, we need an Interceptor, which will be called as a proxy instead of the real service:

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class AopInterceptor implements MethodInterceptor {
 public Object invoke(MethodInvocation invocation) throws Throwable {
 System.out.println("Interceptor: before");
 Object o =  invocation.proceed();
 System.out.println("Interceptor: Done !");
 return o;
 }
}

Finally, we need to use Guice’s Module to configure the binding:

import com.google.inject.AbstractModule;
import com.google.inject.matcher.Matchers;

public class AopModule extends AbstractModule {

 @Override
 protected void configure() {
 bind(BasicDummyService.class);
 bindInterceptor(Matchers.any(),Matchers.annotatedWith(InjectedTransaction.class),new AopInterceptor());
 }
}

Thats it ! Now, when you call the testService() method from a guice injected class, you’ll get the following:

Injector injector = Guice.createInjector(new AopModule());
 BasicDummyService test = injector.getInstance(BasicDummyService.class);
 test.testService();

Result: 

Interceptor: before
doing testService
Interceptor: Done !

The Guice Wiki also has a nice article about AOP with Guice.

This entry was posted in aop, guice, java and tagged , , , . Bookmark the permalink.

Leave a Reply