YMP在线手册
/ 方法拦截(AOP)
方法拦截(AOP)
YMP框架的AOP是基于CGLIB的MethodInterceptor实现的拦截,通过以下注解进行配置:
@Before:用于设置一个类或方法的前置拦截器,声明在类上的前置拦截器将被应用到该类所有方法上;
@After:用于设置一个类或方法的后置拦截器,声明在类上的后置拦截器将被应用到该类所有方法上;
@Clean:用于清理类上全部或指定的拦截器,被清理的拦截器将不会被执行;
@ContextParam:用于设置上下文参数,主要用于向拦截器传递参数配置;
@Ignored:声明一个方法将忽略一切拦截器配置;
说明:
声明@Ignored注解的方法、非公有方法和Object类方法及Object类重载方法将不被拦截器处理。
示例一:
// 创建自定义拦截器
public class DemoInterceptor implements IInterceptor {
public Object intercept(InterceptContext context) throws Exception {
// 判断当前拦截器执行方向
switch (context.getDirection()) {
// 前置
case BEFORE:
System.out.println("before intercept...");
// 获取拦截器参数
String _param = context.getContextParams().get("param");
if (StringUtils.isNotBlank(_param)) {
System.out.println(_param);
}
break;
// 后置
case AFTER:
System.out.println("after intercept...");
}
return null;
}
}
@Bean
public class TestDemo {
@Before(DemoInterceptor.class)
public String beforeTest() {
return "前置拦截测试";
}
@After(DemoInterceptor.class)
public String afterTest() {
return "后置拦截测试";
}
@Before(DemoInterceptor.class)
@After(DemoInterceptor.class)
@ContextParam({
@ParamItem(key = "param", value = "helloworld")
})
public String allTest() {
return "拦截器参数传递";
}
public static void main(String[] args) throws Exception {
YMP.get().init();
try {
TestDemo _demo = YMP.get().getBean(TestDemo.class);
_demo.beforeTest();
_demo.afterTest();
_demo.allTest();
} finally {
YMP.get().destroy();
}
}
}示例二:
@Bean
@Before(DemoInterceptor.class)
@ContextParam({
@ParamItem(key = "param", value = "helloworld")
})
public class TestDemo {
public String beforeTest() {
return "默认前置拦截测试";
}
@After(DemoInterceptor.class)
public String afterTest() {
return "后置拦截测试";
}
@Clean
public String cleanTest() {
return "清理拦截器测试";
}
public static void main(String[] args) throws Exception {
YMP.get().init();
try {
TestDemo _demo = YMP.get().getBean(TestDemo.class);
_demo.beforeTest();
_demo.afterTest();
_demo.cleanTest();
} finally {
YMP.get().destroy();
}
}
}注:@ContextParam注解的value属性允许通过$xxx的格式支持从框架全局参数中获取xxx的值