aspects-js
在nodejs中使用面向切面的变成
只需要使用NPM进行安装
$ npm install --save aspects-js
需要在你的入口文件的最开始的位置引入aspects-js
require('aspects-js');
添加一个切面,这个切面的定义将写在一个新的文件中
首先,需要在这个切面定义文件的最开始的位置引入aspects-js中的Aspect
接口
//文件: testAspect.js
const { Aspect } = require('aspects-js');
其次,在文件中声明自定义的切面类继承Aspect
接口,并重写pointcut
属性的get方法返回切面表达式,同时可以重写面向切点处理的一些方法
//文件: testAspect.js
class TestAspect extends Aspect {
get pointcut() { return '*.do*()' },
before() { console.log('this is for before join point') },
after() { console.log('this is for after join point') }
}
然后,需要将这个自定义的切面类的实例导出
//文件: testAspect.js
module.exports = new TestAspect();
最后,在项目的入口文件(在需要被切面类加载之前)加载指定的切面类实例
//文件: entry.js
require('./testAspect.js');
现在,所有的后续加载的类在执行起方法时将会被自定义的切面类进行切面
Aspect
接口interface Aspect {
readonly pointcut: Pointcut | string | ((joinPoint: JoinPoint) => boolean);
readonly order: number;
after(joinPoint: JoinPoint, result: any, error: Error);
afterReturn(joinPoint: JoinPoint, result: any): any;
afterThrow(joinPoint: JoinPoint, error: Error): void;
before(joinPoint: JoinPoint):void;
around(joinPoint: JoinPoint): any;
}
JoinPoint
类class JoinPoint {
readonly type: Class;
readonly fun: Function;
readonly thisArg: any;
readonly target: any;
readonly args: any[];
proceed(...args: any[]): any;
}
Pointcut
类class Pointcut {
constructor(pointcut: string);
matches(joinPoint: JoinPoint): boolean;
}
"ClassName.FunctionName()"
execution
关键字"execution(ClassName.FunctionName())"
within
关键字"within(ClassName)"
"FunctionName(..)"
"FunctionName(Type1,Type2)"
"FunctionName(Type1,..,Type2)"
*
匹配多个字符 通配符
"*Service.do*()"
匹配所有以Service
结尾的类型中的以do
开头的方法
?
匹配一个字符 通配符
"you?.do?()"
+
针对名称的 或 运算"within(Test1+Test2)"
匹配Test1
或Test2
中所有的方法
|
,||
逻辑 或 运算符"within(Test1)|within(Test2)"
匹配Test1
或Test2
中所有的方法
&
,&&
逻辑 且 运算符"within(Test1)&abc"
匹配Test1
中的abc
方法
!
逻辑 非 运算符"!within(Test)"
匹配所有不在Test
类中的方法
()
括号运算符 (用于逻辑)提升括号内部表达式的优先级
()
方法调用 运算符"abc()"
"abc(..)"
匹配所有的名称为abc
的方法
"abc(Type1)"
匹配所有的名称为abc
且在执行时只传入了一个类型为Type1
的参数的方法
,
参数分割 运算符"*(Type1,Type2)"
匹配所有执行时传入类型依次为Type1
与Type2
两个参数的所有方法
.
属性 运算符"Test.abc()"
匹配Test
类中的abc
方法
..
Multiple arguments operator for arguments匹配连续的多个参数类型
Aspects
接口的order
属性此属性用于控制切面的执行顺序,值越小优先级越高
增加pointcut可以使用函数作为值
接口Aspects
增加属性order
,用于控制切面的执行顺序
在pointcut中使用AST的方式代替正则
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。
1. 开源生态
2. 协作、人、软件
3. 评估模型