aop面向切面编程(aspect oriented programming),是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。spring框架用的核心技术就是aop,是函数式编程的一种衍生范型。利用aop的好处就是可以对业务逻辑进行隔离,降低耦合度,提高程序的可重用性,同时提高了开发的效率。开源的aop也有不少,我这里用的kingaop.
1 项目结构
2 定义一个日志记录的实体类user和loggingaspect切面日志类
1
2
3
4
5
6
7
8
9
10
11
12
13
|
namespace aopdemo.logging { class user { public int id { get ; set ; } public string name { get ; set ; } public string pwd{ get ; set ;} public string ip { get ; set ; } public string state { get ; set ; } public system.datetime logintime { get ; set ; } } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
using system; using system.text; using kingaop.aspects; namespace aopdemo.logging { internal class loggingaspect : onmethodboundaryaspect { public override void onentry(methodexecutionargs args) { string logdata = createlogdata( "entering" , args); console.writeline(logdata); } public override void onexit(methodexecutionargs args) { string logdata = createlogdata( "leaving" , args); console.writeline(logdata); } /// <summary> /// aop对于登录日志逻辑,只需在此进行修改即可,无需修改被切面的处理类 /// </summary> /// <param name="methodstage"></param> /// <param name="args"></param> /// <returns></returns> private string createlogdata( string methodstage, methodexecutionargs args) { var str = new stringbuilder(); str.appendline(); str.appendline( string .format(methodstage + " {0} " , args.method)); foreach (var argument in args.arguments) { var argtype = argument.gettype(); str.append(argtype.name + ": " ); if (argtype == typeof ( string ) || argtype.isprimitive) { str.append(argument); } else { foreach (var property in argtype.getproperties()) { str.appendformat( "{0} = {1}; " , property.name, property.getvalue(argument, null )); } } } return str.tostring(); } } } |
3 login类
该类必须实现idynamicmetaobjectprovider的getmetaobject方法,同时在需要切面的方法上用属性[loggingaspect]进行标注,loggingaspect属性也就是我们上面定义的loggingaspect切片处理类.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
using system.dynamic; using system.linq.expressions; using kingaop; namespace aopdemo.logging { /// <summary> /// 登录逻辑处理,只需添加一个loggingaspect即可实现日志功能,达到逻辑和通用处理的逻辑分离 /// </summary> internal class login : idynamicmetaobjectprovider { //添加登录切面 [loggingaspect] public void loginvaldate(user entity) { //只需进行业务逻辑处理,无需进行日志处理 if (entity.name == "jack" && entity.pwd == "wang" ) { entity.state = "logged" ; } else { entity.state = "error" ; } } /// <summary> /// idynamicmetaobjectprovider的实现 /// </summary> /// <param name="parameter"></param> /// <returns></returns> public dynamicmetaobject getmetaobject(expression parameter) { //need for aop weaving return new aspectweaver(parameter, this ); } } } |
调试代码如下:
1
2
3
4
|
//测试感觉kingaop必须有一个dynamic才能切面 logging.login test = new logging.login(); dynamic entity = new logging.user { name = "jon", id = 99,pwd="wang",state="",logintime=system.datetime.now}; test.loginvaldate(entity); |