当前位置: 首页 > news >正文

Solon2 开发之容器,七、切面与函数环绕拦截

想要环绕拦截一个 Bean 的函数。需要三个前置条件:

  1. 通过注解做为“切点”,进行拦截(不能无缘无故给拦了吧?费性能)
  2. Bean 的 method 是被代理的
  3. 在 Bean 被扫描之前,完成环绕拦截的注册

1、定义切点和注册环绕拦截

Solon 的切点,通过注解实现,得先定义一个。例如:@Logging

//@Target 是决定可以注在什么上面的
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Logging {boolean enable() default true;
}

定义拦截器

//简单点处理
@Slf4j
public class LoggingInterceptor implements Interceptor {@Overridepublic Object doIntercept(Invocation inv) throws Throwable {//此处为拦截处理Object rst = inv.invoke();log.info("Args: {}\nReturn: {}", inv.args(), rst);return rst;}
}//如果需要取注解信息,并进行控制
@Slf4j
public class LoggingInterceptor2 implements Interceptor {@Overridepublic Object doIntercept(Invocation inv) throws Throwable {Logging anno = inv.method().getAnnotation(Logging.class);if (anno == null) {//因为 Logging 支持 ElementType.TYPE,所以也要检查类上的注解anno = inv.target().getClass().getAnnotation(Logging.class);}//此处为拦截处理Object rst = inv.invoke();if(anno != null && anno.enable()){log.info("Args: {}\nReturn: {}", inv.args(), rst);}return rst;}
}

手动注册或关联绑定环绕拦截(二种模式,选一即可)

//手动注册模式
Solon.context().beanAroundAdd(Logging.class, new LoggingInterceptor());//关联绑定模式(通过@Around注解,直接在注解类上关联绑定)
@Around(LoggingInterceptor.class)
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Logging {
}

现在切点定义好了,可以到处“埋”了…

2、应用:把切点“埋”到需要的地方

@Service
public class DemoController{@Loggingpublic void addUser(UserModel user){//...}
}

就这样完成一个面向切面的开发了。

3、通过插件及插件配置,变成一个复用的东西

这是刚才定义注解:

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Logging {
}

开发插件:

@Slf4j
public class XPluginImp implements Plugin {@Overridepublic void start(AopContext context) {context.beanAroundAdd(Logging.class, inv->{Object rst = inv.invoke();log.info("Args: {}\nReturn: {}", inv.args(), rst);});}
}

配置插件:

solon.plugin=xxx.xxx.log.XPluginImp

一个可复用的插件开发完成了。关于Solon插件开发,可参考别的章节内容。

http://www.lryc.cn/news/4200.html

相关文章:

  • 代码随想录第十天(28)
  • 循环队列来了解一下!!
  • Idea打包springboot项目war包,测试通过
  • python+django高校师生健康信息管理系统pycharm
  • CUDA中的流序内存分配
  • 开源、低成本的 Xilinx FPGA 下载器(高速30MHz)
  • Maven专题总结
  • 谷粒商城--SPU和SKU
  • 二叉树OJ题(上)
  • 第一章 PDF语法
  • IntelliJ IDEA 创建JavaFX项目运行
  • IC封装常见形式
  • Linux通配符、转义符讲解
  • [OpenMMLab]提交pr时所需的git操作
  • pandas——groupby操作
  • webpack.config.js哪里找?react项目关闭eslint监测
  • OpenCV 图像梯度算子
  • Linux c编程之Wireshark
  • 极客时间_FlinkSQL 实战
  • Pytorch 混合精度训练 (Automatically Mixed Precision, AMP)
  • 使用太极taichi写一个只有一个三角形的有限元
  • 进程,线程
  • 第03章_基本的SELECT语句
  • 干货 | 简单了解运算放大器...
  • C++定位new用法及注意事项
  • 【Android笔记75】Android之翻页标签栏PagerTabStrip组件介绍及其使用
  • 【Kafka】【二】消息队列的流派
  • 现代 cmake (cmake 3.x) 操作大全
  • how https works?https工作原理
  • Docker的资源控制管理