拦截器的作用原理:
声明拦截器,加@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拦截器的一些基本的认识。