前言
本篇博客我们继续深入spring,还是在原有的基础上进行改造。下面请先欣赏一下博主画的一张aop简图(没有艺术天分,画的不好莫见怪)
解析:往往在我们的系统的多个核心流程中会有一部分与之关系不大的相同的横切流程,例如权限认证,事务管理。因此我们一般会抽象出这些相同的比较次要的交给spring aop的Handler来统一处理这些横切流程也就是上图中绿色部分。接下来我们看一下本例结构图:
解析:1,我们的Hostess对象是Master接口的实现,主要实现了WalkDog()和shopping()两个方法,而WalkDog()方法则是调用的是Dog接口的实现类的bark()方法。
2,我们整个程序的入口Client调用的Hostess对象的两个核心方法,HumanHandler处理的Hostess对象的横切流程。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class Client {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Master master = (Master)context.getBean("humanProxy");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
master.shopping();
master.WalkDog();
}
}
1 | package human; |
解析:通过以上代码我们不难发现我们的程序只是调用核心业务,而往往核心业务的周围有很多繁琐的相对于比较次要的横切业务。利用本例中遛狗,购物之前,我们需要再家做一些前提准备。例如:整理一下着装,锁上房门等等,回家之后有需要换鞋之类的。因此我们还需要一个handler来处理这些业务。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
44package aop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class HumanHandler implements InvocationHandler {
private Object target;// 目标是不固定
public void setTarget(Object target) {
this.target = target;
}
/*
* return 返回是原来目标方法所返回的内容 method 就是要执行的方法
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
before();
// 具体的业务逻辑代码
Object returnValue = method.invoke(target, args);
after();
return returnValue;
}
private void before() {
// 前置任务
System.out.println("[代理执行前置任务]整理着装");
System.out.println("[代理执行前置任务]带上钥匙");
System.out.println("");
System.out.println("[核心业务开始]*****************");
}
private void after() {
// 后置任务
System.out.println("[核心业务结束]*****************");
System.out.println("");
System.out.println("[代理执行后置任务]开门");
System.out.println("[代理执行后置任务]换鞋");
}
}
解析:有了handler我们还需要一个代理工厂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
26package org.springframework.aop.framework;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class ProxyFactoryBean {
private Object target;
private InvocationHandler handler;
public ProxyFactoryBean(Object target,InvocationHandler handler){
this.target = target;
this.handler = handler;
}
//返回本类的一个实例
public Object getProxyBean() throws IllegalArgumentException, InstantiationException, IllegalAccessException, ClassNotFoundException{
Object obj = Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
handler);
return obj;
}
}
解析:接下来我们来看一下本例的具体配置1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="hostess" class="human.Hostess" scope="prototype">
<property name="dog" ref="dog1"></property>
</bean>
<bean id="dog1" class="dog.Taidi" scope="prototype"></bean>
<bean id="dog2" class="dog.Labuladuo" scope="prototype"></bean>
<bean id="humanHandler" class="aop.HumanHandler">
<property name="target" ref="hostess"></property>
</bean>
<bean id="humanProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="handlerName" ref="humanHandler"></property>
<property name="target" ref="hostess"></property>
</bean>
</beans>
最后一步也是关键,本类中使用到的实例需要我们通过读取上面这份配置文件然后通过反射构造出来。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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109package aop;
import java.io.File;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.aop.framework.ProxyFactoryBean;
public class ClassPathXmlApplicationContext implements ApplicationContext {
private String fileName;
public ClassPathXmlApplicationContext(String fileName){
this.fileName = fileName;
}
@Override
public Object getBean(String beanid) {
System.out.println("传递过来的ID:"+beanid);
//获取本类的当前目录
String currentPath = this.getClass().getResource("").getPath().toString();
SAXReader reader = new SAXReader();//DOM4J解释器
Document doc = null;//xml文档本身
Object obj = null;//目标表创建出来的实例
try {
doc = reader.read( new File(currentPath+fileName) );
String xpath = "/beans/bean[@id='"+beanid+"']";
Element beanNode = (Element) doc.selectSingleNode(xpath);
String className = beanNode.attributeValue("class");
if ("org.springframework.aop.framework.ProxyFactoryBean".equals(className)){
Element interceptorNamesNode =
(Element) beanNode.selectSingleNode("property[@name='handlerName']");
String handlerName_value = interceptorNamesNode.attributeValue("ref");
Element targetNode = (Element) beanNode.selectSingleNode("property[@name='target']");
String targetName_value = targetNode.attributeValue("ref");
return forProxyFactoryBean(targetName_value,handlerName_value);
}
obj = Class.forName(className).newInstance();
//查找下一代
Element propertyNode = (Element) beanNode.selectSingleNode("property");
if (propertyNode!=null){
//注入
//System.out.println("发现property节点,准备注入");
//需要注入的属性名
String propertyName = propertyNode.attributeValue("name");
//System.out.println("需要注入的属性:"+propertyName);
//注入方法
String executeMethod = "set"+(propertyName.substring(0, 1)).toUpperCase()+propertyName.substring(1,propertyName.length());
//System.out.println("需要执行注入方法:"+executeMethod);
//需要注入的对象实例
String di_object_name = propertyNode.attributeValue("ref");
//System.out.println("注入的对象是:"+di_object_name);
//定义我们的需要注入的对象实例[递归算法:1.层级是不知道多少层的 2.自己调用自己 3.最后1层会自己结束]
Object di_object = getBean(di_object_name);
//System.out.println("xxx:"+di_object);
//Method method = obj.getClass().getMethod(executeMethod,di_object.getClass().getInterfaces());// new Method(executeMethod);
Method []methods = obj.getClass().getMethods();
for (Method m : methods) {
if(executeMethod.equals(m.getName()) ) {
m.invoke(obj, di_object);
break;
}
}
}
else{
System.out.println("没有属性,结束即可");
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("返回实例:"+obj);
return obj;
}
public Object forProxyFactoryBean(String targetName_value,String handlerName_value) throws Exception{
System.out.println("目标对象"+targetName_value);
Object target = getBean(targetName_value);
System.out.println("代理对象"+handlerName_value);
InvocationHandler handler = (InvocationHandler) getBean(handlerName_value);
return new ProxyFactoryBean(target,handler).getProxyBean();
}
}
运行结果如下:
总结
1 spring aop将我们的系统分为两部分,一核心业务,二横切业务。我们的只需关注核心业务,横切业务统一交给代理去处理。
2 本例依旧是利用反射调用横切方法实现aop,还是那句话,我们自己写的自然是漏洞百出,只是为了说明问题。作为一个开源的框架,如果对spring源码感兴趣的朋友可以自行查看。