/java/

JEE. Simple Interceptor.

2016-03-20 13:01:27

Interceptor

package pl.btbw.core;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
import java.lang.reflect.Method;

public class MethodLogger {

    @AroundInvoke
    public Object log(InvocationContext context) throws Exception {
        final Method method = context.getMethod();
        long start = System.nanoTime();
        try {
            return context.proceed();
        } finally {
            long end = System.nanoTime();
            System.out.println("Method: " + method + " invoked in: " + (end - start) + " nanoseconds");
        }
    }
}

How to use this ?

package pl.btbw;

import pl.btbw.core.MethodLogger;

import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import java.util.Date;

@Stateless
@Interceptors(MethodLogger.class)
public class MainService {

    public String getMessage(String message) {
        return message + " " + new Date();
    }
}

that's all