CDI 组件拦截器的使用和学习

拦截器的作用原理:

声明拦截器,加@Interceptor注解

  方法有二:
  1)为拦截器添加Qualifier;
  2)不添加Qualifier。
为拦截器添加具体的拦截方法,该方法加@AroundInvoke注解
在beans.xml文件中声明拦截器的位置
调用、注入拦截器
  方法有二:
  1)使用Qualifier声明注入的拦截器;
  2)使用注解@Interceptors(xxx.class)来声明注入的拦截器。

拦截器的使用配置:

添加@interceptor注解:

package cn.edu.sdut.r314;

import java.io.Serializable;
import java.util.Date;

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

@Interceptor
public class MyInterceptor implements Serializable {
    public MyInterceptor() {

    }
}

添加具体实现方法:@Aroundlnvoke注解:

@AroundInvoke
    public Object doMy(InvocationContext ctx) throws Exception {
        System.out.println("MyInterceptor is called at: " + new Date());
        return ctx.proceed();
    }
}

在beans.xml文件中声明该拦截器:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
      http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
    <interceptors>
        <class>cn.edu.sdut.r314.MyInterceptor</class>
    </interceptors>
</beans>

调用 和注入拦截器:

package cn.edu.sdut.r314;

import javax.inject.Named;
import javax.interceptor.Interceptors;

/**
 *
 * @author gaoziqiang
 */
@Named
public class RoomController {

    /**
     * 订房
     * @return
     */
    public void checkin(){
        System.out.println("checkin room......");
    }

    /**
     * 退房
     * @return
     */
    //拦截器注入方式一
    //@My
    //拦截器注入方式二
    @Interceptors(MyInterceptor.class)//表示拦截器所在的类
    public void checkout(){
        System.out.println("checkout room......");
    }

}

以上就是对CDI拦截器的一些基本的认识。

 

转载于:https://www.cnblogs.com/taue997/p/11048150.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值