实例分析,AOP的静态代理和动态代理
源码获取github
[TOC]
1.什么是AOP?
Aspect Oriented Programming with Spring 面向切面(方面)编程
- 面向切面编程是面向对象编程的一个补充而已
- 白话:我的理解—->在不改变原来的代码的基础上增强(增加)新的功能
2.代码结构
3.情景描述引发静态代理
如果现在让你完成一个2个数的四则运算
核心业务完成
1
2
3
4
5
6
7
8
9
10
11
12
13
14package com.hs.service;
* 对外提供的核心业务,完成了加法/减法/乘法/除法运算
*/
public interface {
int add(int x, int y);
int sub(int x, int y);
int mul(int x, int y);
int div(int x, int y);
}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
31package com.hs.service;
* 核心代码
*/
public class ArithmeticServiceImpl implements {
public int add(int x, int y) {
//核心代码
int result = x + y;
return result;
}
public int sub(int x, int y) {
int result = x - y;
return result;
}
public int mul(int x, int y) {
int result = x * y;
return result;
}
public int div(int x, int y) {
int result = x / y;
return result;
}
}完成了,和尚—>技术经理—>定义接口,悟空程序员—>接口实现类
交工客户龙王,龙王需要显示传递数据的信息功能—>和尚—>悟空完成客户需求,但是万一如果又不要这个功能呢,现在引出静态代理,在核心代码的基础上增加新的功能
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
36package com.hs.service;
* 新增加的功能,采用静态代理
*/
public class ArithmeticServiceLogImpl implements {
//声明一个核心代码类的变量,为了后面方便调用核心代码的功能
private ArithmeticServiceImpl asc = new ArithmeticServiceImpl();
public int add(int x, int y) {
//后增加的某个功能
System.out.println("加法传递的参数===>x="+x+",y="+y);
// 然后调用核心代码的功能
return asc.add(2, 3);
}
public int sub(int x, int y) {
System.out.println("减法传递的参数===>x="+x+",y="+y);
return asc.sub(2, 3);
}
public int mul(int x, int y) {
System.out.println("乘法传递的参数===>x="+x+",y="+y);
return asc.mul(2, 3);
}
public int div(int x, int y) {
System.out.println("除法传递的参数===>x="+x+",y="+y);
return asc.mul(2, 3);
}
}
测试:
大专栏 Spring学习笔记(十)AOP静态代理和动态代理说明tter">1 |
package com.hs.test; |
4.动态代理
接口和核心代码不变,
代理类:
1 |
package com.hs.proxy; |
测试
1 |
package com.hs.test; |