代理的概念和作用
生活中的代理
例如你去美国买苹果电脑和在中国的零售店买苹果电脑的本质都是一样的,都是要买苹果的电脑,不同的就是,在本地代理商零售店买苹果电脑可能会有一些附加服务,例如送一些简单的配件和在大陆的保修,还有就是省去了你去美国的路费和其它开销。
程序中的代理
要为已存在的多个具有相同接口的目标类的各个方法增加一些系统功能,例如,异常处理、日志、计算方法的运行时间、事务管理、等等。
编写一个与目标类具有相同接口的代理类,代理类的每个方法调用目标类的相同方法,并在调用方法时加上系统功能的代码。
如果采用工厂模式和配置文件的方式进行管理,则不需要修改客户端程序,在配置文件中配置是使用目标类、还是代理类,这样以后很容易切换,譬如,想要日志功能时就配置代理类,否则配置目标类,这样,增加系统功能很容易,以后运行一段时间后,又想去掉系统功能也很容易。
系统中存在交叉业务,一个交叉业务就是要切入到系统中的一个方面,如下所示:
安全 事务 日志
StudentService ----|--------|------------|-------------
CourseService ----|--------|------------|-------------
MiscService ----|--------|------------|-------------
用具体的程序代码描述交叉业务:
method1 method2 method3
{ { {
-----------------------------------------------------------------------------------切面
.... .... ......
-----------------------------------------------------------------------------------切面
} } }
交叉业务的编程问题即为面向方面的编程(Aspect oriented program ,简称AOP),AOP的目标就是要使交叉业务模块化。可以采用将切面代码移动到原始方法的周围,这与直接在方法中编写切面代码的运行效果是一样的,如下所示:
-------------------------------------------------------------------------------------切面
func1 func2 func3
{ { {
.... .... ......
} } }
-------------------------------------------------------------------------------------切面
使用代理技术正好可以解决这种问题,代理是实现AOP功能的核心和关键技术。
动态代理技术
要为系统中的各种接口的类增加代理功能,那将需要太多的代理类,全部采用静态代理方式,将是一件非常麻烦的事情!写成百上千个代理类,这样太累了。
JVM可以在运行期动态生成出类的字节码,这种动态生成的类往往被用作代理类,即动态代理类。
JVM生成的动态类必须实现一个或多个接口,所以,JVM生成的动态类只能用作具有相同接口的目标类的代理。
CGLIB库可以动态生成一个类的子类,一个类的子类也可以用作该类的代理,所以,如果要为一个没有实现接口的类生成动态代理类,那么可以使用CGLIB库。
代理类的各个方法中通常除了要调用目标的相应方法和对外返回目标返回的结果外,还可以在代理方法中的如下四个位置加上系统功能代码:
1.在调用目标方法之前
2.在调用目标方法之后
3.在调用目标方法前后
4.在处理目标方法异常的catch块中
分析JVM动态生成的类
public class Proxy
extends Object
implements Serializable
Proxy 提供用于创建动态代理类和实例的静态方法,它还是由这些方法创建的所有动态代理类的超类。
创建某一接口 Foo 的代理:
InvocationHandler handler = new MyInvocationHandler(...);
Class proxyClass = Proxy.getProxyClass(
Foo.class.getClassLoader(), new Class[] { Foo.class });
Foo f = (Foo) proxyClass.
getConstructor(new Class[] { InvocationHandler.class }).
newInstance(new Object[] { handler });
或使用以下更简单的方法:
Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
new Class[] { Foo.class },
handler);
public static Class<?> getProxyClass(ClassLoader loader,
Class<?>... interfaces)
throws IllegalArgumentException
返回代理类的 java.lang.Class 对象,并向其提供类加载器和接口数组。该代理类将由指定的类加载器定义,并将实现提供的所有接口。如果类加载器已经定义了具有相同排列接口的代理类,那么现有的代理类将被返回;否则,类加载器将动态生成并定义这些接口的代理类。
例子:
package cn.cast.day3;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collection;
public class ProxyTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Class clazzProxy1=Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
System.out.println(clazzProxy1.getName());
System.out.println("---------------begin constructors list--------------");
Constructor[] constructors=clazzProxy1.getConstructors();
for(Constructor constructor:constructors){
String name=constructor.getName();
StringBuilder sBuilder =new StringBuilder(name);
sBuilder.append('(');
Class[] clazzParams=constructor.getParameterTypes();
for(Class clazzParam:clazzParams){
sBuilder.append(clazzParam.getName()).append(',');
}
if(clazzParams!=null && clazzParams.length!=0){
sBuilder.deleteCharAt(sBuilder.length()-1);
}
sBuilder.append(')');
System.out.println(sBuilder.toString());
}
System.out.println("---------------begin methods list--------------");
Method[] methods=clazzProxy1.getMethods();
for(Method method:methods){
String name=method.getName();
StringBuilder sBuilder =new StringBuilder(name);
sBuilder.append('(');
Class[] clazzParams=method.getParameterTypes();
for(Class clazzParam:clazzParams){
sBuilder.append(clazzParam.getName()).append(',');
}
if(clazzParams!=null && clazzParams.length!=0){
sBuilder.deleteCharAt(sBuilder.length()-1);
}
sBuilder.append(')');
System.out.println(sBuilder.toString());
}
}
}
结果:
$Proxy0
---------------begin constructors list--------------
$Proxy0(java.lang.reflect.InvocationHandler)
---------------begin methods list--------------
hashCode()
equals(java.lang.Object)
toString()
add(java.lang.Object)
contains(java.lang.Object)
isEmpty()
size()
toArray([Ljava.lang.Object;)
toArray()
addAll(java.util.Collection)
iterator()
remove(java.lang.Object)
clear()
containsAll(java.util.Collection)
removeAll(java.util.Collection)
retainAll(java.util.Collection)
isProxyClass(java.lang.Class)
getProxyClass(java.lang.ClassLoader,[Ljava.lang.Class;)
getInvocationHandler(java.lang.Object)
newProxyInstance(java.lang.ClassLoader,[Ljava.lang.Class;,java.lang.reflect.InvocationHandler)
getClass()
notify()
notifyAll()
wait()
wait(long)
wait(long,int)
package cn.cast.day3;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
public class ProxyTest {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
System.out.println("---------------begin create instance object--------------");
Class clazzProxy1=Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
//clazzProxy1.newInstance(); //调用不带参数的构造方法。
Constructor constructor=clazzProxy1.getConstructor(InvocationHandler.class);
/*Collection proxy1=(Collection)constructor.newInstance(new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
return null;
}
});*/
Collection proxy2=(Collection)Proxy.newProxyInstance(
Collection.class.getClassLoader(),
new Class[]{Collection.class},
new InvocationHandler(){
ArrayList target=new ArrayList();
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
//ArrayList target=new ArrayList();
long beginTime=System.currentTimeMillis();
Object retVal=method.invoke(target, args);
long endTime=System.currentTimeMillis();
System.out.println(method.getName()+"running time of:"+(endTime-beginTime));
// TODO Auto-generated method stub
return retVal;
}
}
);
proxy2.add("张三");
proxy2.add("李四");
proxy2.add("王五");
System.out.println(proxy2.size());
}
}
结果:
---------------begin create instance object--------------
addrunning time of:0
addrunning time of:0
addrunning time of:0
sizerunning time of:0
3
分析动态生成的类的内部代码
// 假设需代理接口 Simulator
public interface Simulator {
short simulate(int arg1, long arg2, String arg3) throws ExceptionA, ExceptionB;
}
// 假设代理类为 SimulatorProxy, 其类声明将如下
final public class SimulatorProxy implements Simulator {
// 调用处理器对象的引用
protected InvocationHandler handler;
// 以调用处理器为参数的构造函数
public SimulatorProxy(InvocationHandler handler){
this.handler = handler;
}
// 实现接口方法 simulate
public short simulate(int arg1, long arg2, String arg3)
throws ExceptionA, ExceptionB {
// 第一步是获取 simulate 方法的 Method 对象
java.lang.reflect.Method method = null;
try{
method = Simulator.class.getMethod(
"simulate",
new Class[] {int.class, long.class, String.class} );
} catch(Exception e) {
// 异常处理 1(略)
}
// 第二步是调用 handler 的 invoke 方法分派转发方法调用
Object r = null;
try {
r = handler.invoke(this,
method,
// 对于原始类型参数需要进行装箱操作
new Object[] {new Integer(arg1), new Long(arg2), arg3});
}catch(Throwable e) {
// 异常处理 2(略)
}
// 第三步是返回结果(返回类型是原始类型则需要进行拆箱操作)
return ((Short)r).shortValue();
}
}
动态生成的类实现了Collection接口(可以实现若干接口),生成的类有Collection接口中的所有方法和一个如下接受InvocationHandler参数的构造方法。
构造方法接受一个InvocationHandler对象,接受对象了要干什么用呢?该方法内部的代码:
$Proxy0 implements Collection
{
InvocationHandler handler;
public $Proxy0(InvocationHandler handler)
{
this.handler = handler;
}
}
实现Collection接口的动态类中的各个方法的代码又是怎样的呢?InvocationHandler接口中定义的invoke方法接受的三个参数又是什么意思?
$Proxy0 implements Collection
{
InvocationHandler handler;
public $Proxy0(InvocationHandler handler)
{
this.handler = handler;
}
//生成的Collection接口中的方法的运行原理
int size()
{
return handler.invoke(this,Collection.getClass().getMethod("size"),null);
}
void clear(){
handler.invoke(this,Collection.getClass().getMethod("clear"),null);
}
boolean add(Object obj){
handler.invoke(this,Collection.getClass().getMethod("add",new Class[]{Object.class}),obj);
}
}
图解说明如下:
动态代理的工作原理图:
编写可生成代理和插入通告的通用方法
package cn.cast.day3;
//Advice.java
import java.lang.reflect.Method;
public interface Advice {
public void beforeMethod(Method method);
public void afterMethod(Method method);
}
package cn.cast.day3;
//MyAdvice.java
import java.lang.reflect.Method;
public class MyAdvice implements Advice{
long beginTime=0;
public void beforeMethod(Method method){
System.out.println("start...");
beginTime=System.currentTimeMillis();
}
public void afterMethod(Method method){
System.out.println("end...");
long endTime=System.currentTimeMillis();
System.out.println(method.getName()+"running time of:"+(endTime-beginTime));
}
}
package cn.cast.day3;
//ProxyTest.java
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
public class ProxyTest {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
final ArrayList target=new ArrayList();
Collection proxy2 = (Collection)getProxy(target,new MyAdvice());
proxy2.add("张三");
proxy2.add("李四");
proxy2.add("王五");
System.out.println(proxy2.size());
}
private static Object getProxy(final Object target,final Advice advice) {
Object proxy=Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler(){
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
advice.beforeMethod(method);
Object retVal=method.invoke(target, args);
advice.afterMethod(method);
return retVal;
}
}
);
return proxy;
}
}
结果:
start...
end...
addrunning time of:0
start...
end...
addrunning time of:0
start...
end...
addrunning time of:0
start...
end...
sizerunning time of:0
3
实现类似spring的可配置的AOP框架
工厂类BeanFactory负责创建目标类或代理类的实例对象,并通过配置文件实现切换。其getBean方法根据参数字符串返回一个相应的实例对象,如果参数字符串在配置文件中对应的类名不是ProxyFactoryBean,则直接返回该类的实例对象,否则,返回该类实例对象的getProxy方法返回的对象。
BeanFactory的构造方法接收代表配置文件的输入流对象,配置文件格式如下:
#xxx=java.util.ArrayList
xxx=cn.itcast.ProxyFactoryBean
xxx.target=java.util.ArrayList
xxx.advice=cn.itcast.MyAdvice
ProxyFacotryBean充当封装生成动态代理的工厂,需要为工厂类提供哪些配置参数信息?
目标
通知
编写客户端应用:
编写实现Advice接口的类和在配置文件中进行配置
调用BeanFactory获取对象
在cn.cast.day3.aopframework包下:
package cn.cast.day3.aopframework;
//BeanFactory.java
import java.io.InputStream;
import java.util.Properties;
import cn.cast.day3.Advice;
public class BeanFactory {
Properties props=new Properties();
public BeanFactory(InputStream ips){
try {
props.load(ips);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public Object getBean(String name){
String className = props.getProperty(name);
Object bean=null;
try {
Class clazz=Class.forName(className);
bean =clazz.newInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(bean instanceof ProxyFactoryBean){
Object proxy=null;
try {
ProxyFactoryBean proxtFactorybean = (ProxyFactoryBean) bean;
Advice advice = (Advice)Class.forName(props.getProperty(name + ".advice"))
.newInstance();
Object target = Class.forName(props.getProperty(name + ".target"))
.newInstance();
proxtFactorybean.setAdvice(advice);
proxtFactorybean.setTarget(target);
proxy = ((ProxyFactoryBean) bean).getProxy();
} catch (Exception e) {
e.printStackTrace();
}
return proxy;
}
return bean;
}
}
package cn.cast.day3.aopframework;
//ProxyFactoryBean.java
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import cn.cast.day3.Advice;
public class ProxyFactoryBean {
private Advice advice;
private Object target;
public Object getProxy(){
Object proxy=Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler(){
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
advice.beforeMethod(method);
Object retVal=method.invoke(target, args);
advice.afterMethod(method);
return retVal;
}
}
);
return proxy;
}
public Advice getAdvice() {
return advice;
}
public void setAdvice(Advice advice) {
this.advice = advice;
}
public Object getTarget() {
return target;
}
public void setTarget(Object target) {
this.target = target;
}
}
package cn.cast.day3.aopframework;
//AopFrameworkTest.java
import java.io.InputStream;
public class AopFrameworkTest {
public static void main(String[] args){
InputStream ips=AopFrameworkTest.class.getResourceAsStream("config.properties");
Object bean=new BeanFactory(ips).getBean("xxx");
System.out.println(bean.getClass().getName());
}
}
config.properties文件:
#xxx=java.util.ArrayList
xxx=cn.cast.day3.aopframework.ProxyFactoryBean
xxx.advice=cn.cast.day3.MyAdvice
xxx.target=java.util.ArrayList
结果:
$Proxy0
当把config.properties文件更改为:
xxx=java.util.ArrayList
#xxx=cn.cast.day3.aopframework.ProxyFactoryBean
xxx.advice=cn.cast.day3.MyAdvice
xxx.target=java.util.ArrayList
结果:
java.util.ArrayList