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})

转载于:https://my.oschina.net/DreamZhong/blog/282953

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值