通过动态代理模拟Spring AOP
1.包名:
com.bestaone.aop
2.包含class文件:
AOPFactory.java AOP工厂
AopHandler.java 代理类
ClientTest.java 测试类
FunListener.java 模拟权限易做图
Listener.java 易做图接口
LogListener.java 模拟日志易做图
3.具体类容
AOPFactory.java AOP工厂
[java]
package com.bestaone.aop;
/**
* AOP工厂
* @author 张国圣
*/
public class AOPFactory {
/**
* 实例化对象
* @param clzzName
* @return
*/
private static Object getClassInstance(String clzzName) {
Object obj = null;
try {
Class cls = Class.forName(clzzName);
obj = (Object) cls.newInstance();
}catch (Exception e) {
e.printStackTrace();
}
return obj;
}
/**
* 创建代理类,并添加易做图
* @param clzzName
* @param listenerName 易做图
* @return 代理类
*/
public static Object getAOPProxyedObject(String clzzName, String[] listenerName) {
Object proxy = null;
Listener[] listeners = null;
if(listenerName!=null && listenerName.length>0){
listeners = new Listener[listenerName.length];
for(int i=0;i<listeners.length;i++){
listeners[i] = (Listener)getClassInstance(listenerName[i]);
}
} www.zzzyk.com
AopHandler handler = new AopHandler();
Object obj = getClassInstance(clzzName);
proxy = handler.bind(obj,listeners);
return proxy;
}
}
AopHandler.java 代理类
[java]
package com.bestaone.aop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* 代理类
* @author 张国圣
*/
public class AopHandler implements InvocationHandler{
private Object proxyObj;
private Listener[] listeners;
public Object bind(Object obj,Listener[] listeners) {
this.proxyObj = obj;
this.listeners = listeners;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInte易做图ces(), this);
}
/**
* 由于线程的关系,打印的顺序不是我们想要的,但这不影响这个说明AOP!
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
try {
if(listeners!=null){
this.before(proxy, method, args);
}
result = method.invoke(proxyObj, args);
if(listeners!=null){
this.after(proxy, method, args);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 方法前监听
* @param proxy
* @param method
* @param args
*/
public void before(Object proxy, Method method, Object[] args){
for(int i=0;i<listeners.length;i++){
listeners[i].before(proxy, method, args);
}
}
/**
* 方法后监听
* @param proxy
* @param method
* @param args
*/
public void after(Object proxy, Method method, Object[] args){
for(int i=listeners.length-1;i>=0;i--){
listeners[i].after(proxy, method, args);
}
}
}
ClientTest.java 测试类
[java]
package com.bestaone.aop;
import com.bestaone.UserService;
/**
* 使用代理实现AOP拦截
* @author 张国圣
*/
public class ClientTest {
public static void main(String[] args) {
//要除去AOP拦截,只需设置listenerName=null就可以了
String[] listenerName = {"com.bestaone.aop.FunListener","com.bestaone.aop.LogListener"};
UserService userService = (Us
补充:软件开发 , Java ,