November 17, 2017

Java EE 7 Cross Cutting Interceptor Example

Lets say you need a logging feature for all you business class. Instead of writing repeatable code in yours businesses classes, lets use a Java EE 7 interceptor instead.

package se.magnuskkarlsson.example.javaee7;

import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class TraceLogger {

    private final Logger log = Logger.getLogger(AuditLogger.class.getName());

    @AroundInvoke
    public Object intercept(InvocationContext ctx) throws Exception {
        String className = ctx.getTarget().getClass().getName();
        String methodName = ctx.getMethod().getName();
        List<Object> paramaters = Arrays.asList(ctx.getParameters());
        log.info(className + "#" + methodName + " Starting " + paramaters + " ...");
        Object object = null;
        try {
            object = ctx.proceed();
        } finally {
            log.info(className + "#" + methodName + " Finished.");
        }
        return object;
    }

}

And to use it.

package se.magnuskkarlsson.example.javaee7.control;

import javax.interceptor.Interceptors;
import se.magnuskkarlsson.example.javaee7.AuditLogger;

@Stateless
@Interceptors(TraceLogger.class)
public class EmployeeBean {
...
// public business method goes here...
}

And to make CDI work you need WEB-INF/beans.xml. Note that in Java EE 7 you need to declare your interceptors in beans.xml, that you used to in Java EE 6.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
    bean-discovery-mode="all">
</beans>

No comments: