几段代码让你明白AOP和struts2中拦截器的原理
程序员文章站
2022-05-28 15:50:46
...
代码是李刚老师书上的源码,有助于我们理解动态代理的原理。
Dog.java
DogImpl.java
Dog.java
package lee;
/*
* @author yeeku.H.lee [email protected]
* @version 1.0
* <br>Copyright (C), 2005-2008, yeeku.H.Lee
* <br>This program is protected by copyright laws.
* <br>Program Name:
* <br>Date:
*/
public interface Dog
{
public void info();
public void run();
}
DogImpl.java
package lee;
/*
* @author yeeku.H.lee [email protected]
* @version 1.0
* <br>Copyright (C), 2005-2008, yeeku.H.Lee
* <br>This program is protected by copyright laws.
* <br>Program Name:
* <br>Date:
*/
public class DogImpl implements Dog
{
public void info()
{
System.out.println("我是一只猎狗");
}
public void run()
{
System.out.println("我奔跑迅速");
}
}
package lee;
/**
* @author yeeku.H.lee [email protected]
* @version 1.0
* <br>Copyright (C), 2005-2008, yeeku.H.Lee
* <br>This program is protected by copyright laws.
* <br>Program Name:
* <br>Date:
*/
public class DogIntercepter
{
public void method1()
{
System.out.println("=====模拟通用方法一=====");
}
public void method2()
{
System.out.println("=====模拟通用方法二=====");
}
}
package lee;
import java.lang.reflect.*;
/*
* @author yeeku.H.lee [email protected]
* @version 1.0
* <br>Copyright (C), 2005-2008, yeeku.H.Lee
* <br>This program is protected by copyright laws.
* <br>Program Name:
* <br>Date:
*/
public class MyProxyFactory
{
/**
* 实例Service对象。
* @param serviceName String
* @return Object
*/
public static Object getProxy(Object object)
{
//Dog控制类 代理的操作类
ProxyHandler handler = new ProxyHandler();
//把该dog实例托付给代理操作
handler.setTarget(object);
//第一个参数是用来创建 动态代理 的ClassLoader对象,只要该对象能访问Dog接口即可。
//也就只要DogImpl与Dog在同一
return Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(),handler);
}
}
package lee;
import java.lang.reflect.*;
import java.util.*;
/*
* @author yeeku.H.lee [email protected]
* @version 1.0
* <br>Copyright (C), 2005-2008, yeeku.H.Lee
* <br>This program is protected by copyright laws.
* <br>Program Name:
* <br>Date:
*/
public class ProxyHandler implements InvocationHandler
{
private Object target;
DogIntercepter di = new DogIntercepter();
public Object invoke(Object proxy, Method method, Object[] args)throws Exception
{
Object result = null;
if (method.getName().equals("info"))
{
di.method1();
result =method.invoke(target, args);
di.method2();
}
else
{
result =method.invoke(target, args);
}
return result;
}
public void setTarget(Object o)
{
this.target = o;
}
}
package lee;
/*
* @author yeeku.H.lee [email protected]
* @version 1.0
* <br>Copyright (C), 2005-2008, yeeku.H.Lee
* <br>This program is protected by copyright laws.
* <br>Program Name:
* <br>Date:
*/
public class TestDog
{
public static void main(String[] args)
{
Dog targetObject = new DogImpl();
Dog dog = null;
Object proxy = MyProxyFactory.getProxy(targetObject);
if (proxy instanceof Dog)
{
dog = (Dog)proxy;
}
dog.info();
dog.run();
}
}