Interceptors in Guice – how to log execution method time example

Opublikowany

Google Guice is commonly perceived as more light solution that Spring. That’s why some applications which do not want to have Spring / Spring Boot use it.
More about guice could be found at guice wiki page – https://github.com/google/guice/wiki
One of the cool features that guice provide to developers are interceptors. They are officially called AOP in Guice documentation, which in fact is true You can create aspects oriented programming using interceptors in guice.

Base approach contains following steps
Creation of annotation to mark method that we would like to intercept
Mark method with annotation
Creation of method interceptor
Binding interceptor in module

So if we would like to create interceptor that logs method execution time it should look like that

Annotation
Retention(RetentionPolicy.RUNTIME) Target(ElementType.METHOD)
public @interface FullyLogged {
}

Method mark
@ FullyLogged
public void someMethod() { … }

Interceptor
public class LoggingInterceptor implements MethodInterceptor { private final static Logger LOGGER = LoggerFactory.getLogger(LoggingInterceptor.class);

@Override public Object invoke(final MethodInvocation invocation) throws Throwable { final Stopwatch stopwatch = Stopwatch.createStarted(); final Object returnedObject = invocation.proceed(); LOGGER.info(„Response time from method: „ + invocation.getMethod().getName() + „ of class: „ + invocation.getMethod().getDeclaringClass().getName() +” is: „ + stopwatch.stop().toString()); return returnedObject; } }

Binding
public class MyModule extends AbstractModule {

bindInterceptor(Matchers.any(), Matchers.annotatedWith(FullyLogged.class), new LoggingInterceptor()); }

In my opinion interceptors could make developers life easier but like all AOP should be used wise.
Typical for security or logging.

Best regards
TJ

Autor
Kategorie Java