实现Interceptor接口
public class DemoInterceptor implements Interceptor{ public void intercept(Invocation invocation) { System.out.println("类拦截器触发方法前"); invocation.invoke(); System.out.println("类拦截器触发方法后"); }}
以下为Invocation中的方法:
|
Before注解,可配置Class、Method级别的的拦截器
// 配置一个Class级别的拦截器,她将拦截本类中的所有方法@Before(AaaInter.class)public class BlogController extends Controller {// 配置多个Method级别的拦截器, 仅拦截本方法@Before({BbbInter.class, CccInter.class})public void index() {}// 未配置Method级别拦截器, 但会被Class级别拦截器AaaInter所拦截public void show() {}}
全局拦截器
public void configInterceptor(Interceptors me) { //控制层拦截器 发起action请求时,调用 me.addGlobalActionInterceptor(new GlobalActionInterceptor()); //服务层拦截器 //使用Duang.duang(),Enhancer.enhance(),Controller.enhance()调用方法时,调用 me.addGlobalServiceInterceptor(new GlobalServiceInterceptor()); }
Inject 拦截器
public void injectDemo() {// 为enhance方法传入的拦截器称为Inject拦截器,下面代码中的Tx称为Inject拦截器OrderService service = Enhancer.enhance(OrderService.class, Tx.class);service.payment(…);}
Inject拦截器可被认为是Class级拦截器,但是次序在Class级拦截器前
Clear 注解用于清除声明在 Method 以外的拦截器,也即只能清除 Global、 Class 或 Inject
拦截器。 Clear 用法记忆技巧: 不带参数时清除所有拦截器 带上参数时只清除该参数指定的拦截器 清除操作仅作用于 Method 之外声明的拦截器