aop面向切面编程的原理就是对java代理模式的应用。
java代理分为动态代理和静态代理,这里只介绍动态代理。
先举个例子(代理例子):小明想去阿里面试,他需要先在给阿里的官网或者某些招聘网站投递简历,然后hr看到简历,筛选以后觉得合格后再给小明打电话约面试,面试完以后,会给小明通知面试结果。这里hr可以作为一个代理,作为阿里公司的代理,在面试之前要筛选简历,在面试完成之后要通知小明,可以理解为前置通知和后置通知。
第二个例子(aop例子):我想写一篇博客,所以我需要一台电脑,我在写博客之前要先打开电脑,写完以后要关闭电脑。同样,我想用电脑干任何人事情都是这么一个逻辑,那么我任务电脑在工作之前要先开机,工作完成以后要关机。于是就有了aop,面向切面中的切面。
代码示例:
//电脑的接口
public interface Computer {
void work();
}
//戴尔电脑
public class DellPc implements Computer {
@Override
public void work() {
System.out.println("DellPc Is Working");
}
}
//通知的接口,这里为了简单只做了前置和后置
public interface AdviceExcute {
Object beforeMethod(Object object, Method method, Object[] args);
Object afterMethod(Object object, Method method, Object[] args);
}
//电脑前置后置通知的实现类
public class ComputerAdvice implements AdviceExcute {
@Override
public Object beforeMethod(Object object, Method method, Object[] args) {
System.out.println(object.getClass().getName() +"类的"+method.getName()+"的前置方法执行,参数为:"+args);
return null;
}
@Override
public Object afterMethod(Object object, Method method, Object[] args) {
System.out.println(object.getClass().getName() +"类的"+method.getName()+"的后置方法执行,参数为:"+args);
return null;
}
}
//advice.xml配置文件
<?xml version="1.0" encoding="utf-8" ?>
<advices>
<advice-before class="com.jshq.wqx.Computer" method="work" excute-class="com.jshq.wqx.ComputerAdvice"/>
<advice-after class="com.jshq.wqx.Computer" method="work" excute-class="com.jshq.wqx.ComputerAdvice"/>
</advices>
//代理工厂类
package com.jshq.wqx;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import sun.security.util.Length;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashSet;
import java.util.Set;
/**
* @author ******
* @Date 2018/10/24
*/
public class ProxyFacoty<T> {
private static final String ClASS_ATTR_NAME = "class";
private static final String METHOD_ATTR_NAME = "method";
private static final String TYPE_ATTR_NAME = "type";
private static final String EXCUTE_CLASS_ATTR_NAME = "excute-class";
private static final String EXCUTE_METHOD_ATTR_NAME = "excute-method";
private static final String TYPE_ATTR_VALUE_BEFORE = "before";
private static final String TYPE_ATTR_VALUE_AFTER = "after";
//private static final String BEFROE_METHOD_NAME = "beforeMethod";
private Set<Element> beforeElementSet = new HashSet<>();
private Set<Element> afterElementSet = new HashSet<>();
Set<String> beforeclassMethodSet = new HashSet<>();
Set<String> afterclassMethodSet = new HashSet<>();
private T t;
public ProxyFacoty(T t){
this.t =t;
}
public T getProxyInstance(){
return (T) Proxy.newProxyInstance(
t.getClass().getClassLoader(),
t.getClass().getInterfaces(),
(proxy, method, args) -> {
Object returnValue = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document adviceDoc = db.parse("src/advice.xml");
//前置
NodeList beforeAdvices = adviceDoc.getElementsByTagName("advice-before");
handleBeforeAdvice(beforeAdvices,method,args);
method.invoke(t,args);
//后置
NodeList afterAdvices = adviceDoc.getElementsByTagName("advice-after");
handleAfterAdvice(afterAdvices,method,args);
//执行目标对象方法
return returnValue;
}
);
}
/**
* 处理前置通知节点
* @param beforeAdvices
* @param method
* @param args
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
*/
private void handleBeforeAdvice(NodeList beforeAdvices, Method method, Object... args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
for (int i = 0; i<beforeAdvices.getLength();i++) {
Element beforeAdvice = (Element) beforeAdvices.item(i);
if(beforeclassMethodSet.add("advice-before"+beforeAdvice.getAttribute(ClASS_ATTR_NAME)
+beforeAdvice.getAttribute(METHOD_ATTR_NAME))){
beforeElementSet.add(beforeAdvice);
}else{
throw new RuntimeException();
}
}
for (Element advice : beforeElementSet){
String className = advice.getAttribute(ClASS_ATTR_NAME);
String methodName = advice.getAttribute(METHOD_ATTR_NAME);
String type = advice.getAttribute(TYPE_ATTR_NAME);
String excuteClassName = advice.getAttribute(EXCUTE_CLASS_ATTR_NAME);
boolean classFlag = className.equals(t.getClass().getName());
if(!classFlag){
for (Class clsss : t.getClass().getInterfaces()){
if(clsss.getName().equals(className)){
classFlag = true;
break;
}
}
}
if(classFlag && methodName.equals(method.getName())){
AdviceExcute excute = (AdviceExcute) Class.forName(excuteClassName).newInstance();
if(excute!=null){
excute.beforeMethod(t,method,args);
}
}
}
}
/**
* 处理后置通知节点
* @param afterAdvices
* @param method
* @param args
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
*/
private void handleAfterAdvice(NodeList afterAdvices, Method method, Object... args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
for (int i = 0; i<afterAdvices.getLength();i++) {
Element afterAdvice = (Element) afterAdvices.item(i);
if(afterclassMethodSet.add("advice-after"+afterAdvice.getAttribute(ClASS_ATTR_NAME)
+afterAdvice.getAttribute(METHOD_ATTR_NAME))){
afterElementSet.add(afterAdvice);
}else{
throw new RuntimeException();
}
}
for (Element advice : beforeElementSet){
String className = advice.getAttribute(ClASS_ATTR_NAME);
String methodName = advice.getAttribute(METHOD_ATTR_NAME);
String type = advice.getAttribute(TYPE_ATTR_NAME);
String excuteClassName = advice.getAttribute(EXCUTE_CLASS_ATTR_NAME);
boolean classFlag = className.equals(t.getClass().getName());
if(!classFlag){
for (Class clsss : t.getClass().getInterfaces()){
if(clsss.getName().equals(className)){
classFlag = true;
break;
}
}
}
if(classFlag && methodName.equals(method.getName())){
AdviceExcute excute = (AdviceExcute) Class.forName(excuteClassName).newInstance();
if(excute!=null){
excute.afterMethod(t,method,args);
}
}
}
}
}
//电脑代理类
public class ComputerProxy implements InvocationHandler {
private Computer dellPc = new DellPc();
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("proxyClass is working");
method.invoke(dellPc,args);
return null;
}
}
//main方法
public static void main(String[] args) {
Computer c = new DellPc();
ProxyFacoty<Computer> p = new ProxyFacoty<>(c);
p.getProxyInstance().work();
}
}