EJB3 Interceptors

EJB3中创建Interceptors可以有多种方式

第一种方式可以在EJB Bean中利用@AroundInvoke定义拦截方法, 方法名可以任意指定,方法参数只能有一个,且类型为InvocationContext,

返回值也必须为Object,在EJB Bean中定义的拦截方法只对当前Bean有效

@AroundInvoke
    public Object calculateWastedTime(InvocationContext context) throws Exception {
        long start = System.currentTimeMillis();
        Object result = context.proceed();
        long end = System.currentTimeMillis();
        String methodName = context.getMethod().getName();
        System.out.println("Wasted time of executing the method named " + methodName + ": " + (end - start) + "ms");
        return result;
    }



第二种方式可以专门定义一个拦截类来对需要拦截的EJB Bean进行拦截,如下是一个计算执行方法所用时间的拦截器

package com.icode.jejb.interceptor;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

/**
 * Created with IntelliJ IDEA.
 * User: ZhongGang
 * Date: 14-6-22
 * Time: 下午10:04
 */
public class TimeWastedInterceptor {

    @AroundInvoke
    public Object calculateWastedTime(InvocationContext context) throws Exception {
        long start = System.currentTimeMillis();
        Object result = context.proceed();
        long end = System.currentTimeMillis();
        String methodName = context.getMethod().getName();
        System.out.println("Wasted time of executing the method named " + methodName + ": " + (end - start) + "ms");
        return result;
    }
}



并在相应需要拦截的EJB Bean上注解@Interceptors(value = {TimeWastedInterceptor.class})

你可能感兴趣的:(Interceptor,EJB3,interceptors)