动态代理

动态代理

  程序中的代理

    代理可以为已存在的多个具有相同接口的目标类的各个方法增加一些系统功能,例如,异常处理、日志、计算方法的运行时间、事务管理、

    编写一个与目标类具有相同接口的代理类,代理类的每个方法调用目标类的相同方法,并在调用方法时加上系统功能的代码。

    如果采用工厂模式和配置文件的方式进行管理,则不需要修改客户端程序,在配置文件中配置是使用目标类、还是代理类,这样以后很容易切换,譬如,想要日志功能时就配置代理类,否则配置目标类,这样,增加系统功能很容易,以后运行一段时间后,又想去掉系统功能也很容易。

     

   从上面的图可以看出,代理类和目标类需要集成相同的接口,而代理类的方法运行中调用了目标类的方法,这样就可以实现在目标类的前后添加需要的功能,最后在客户端中根据接口引用不同的类就可以实现代理类和目标类的切换.

   系统中存在交叉业务,一个交叉业务就是要切入到系统中的一个方面

     交叉业务的编程问题即为面向方面的编程(Aspect oriented program ,简称AOP),AOP的目标就是要使交叉业务模块化。可以采用将切面代码移动到原始方法的周围,这与直接在方法中编写切面代码的运行效果是一样的,使用代理技术正好可以解决这种问题,代理是实现AOP功能的核心和关键技术。


  动态代理技术

   要为系统中的各种接口的类增加代理功能,那将需要太多的代理类,全部采用静态代理方式,将是一件非常麻烦的事情!写成百上千个代理类,是不是太累!

      JVM可以在运行期动态生成出类的字节码,这种动态生成的类往往被用作代理类,即动态代理类。

     JVM生成的动态类必须实现一个或多个接口,所以,JVM生成的动态类只能用作具有相同接口的目标类的代理。

      CGLIB库可以动态生成一个类的子类,一个类的子类也可以用作该类的代理,所以,如果要为一个没有实现接口的类生成动态代理类,那么可以使用CGLIB库。

   代理类的各个方法中通常除了要调用目标的相应方法和对外返回目标返回的结果外,还可以在代理方法中的如下四个位置加上系统功能代码:

       1.在调用目标方法之前

       2.在调用目标方法之后

       3.在调用目标方法前后

       4.在处理目标方法异常的catch块中

  动态生成类

  创建动态类的实例对象

    用反射获得构造方法

    编写一个InvocationHandler

    调用构造方法创建动态类的实例对象,并将编写的InvocationHandler类的实例对象传进去

    打印创建的对象和调用对象的没有返回值的方法和getClass方法,

    将创建动态类的实例对象的代理改成匿名内部类的形式编写,锻炼大家习惯匿名内部类。

  

   jvm创建动态类及其实例对象,需要给它提供三个方面信息

        生成的类中有哪些方法,通过让其实现哪些接口的方式进行告知;

        产生的类字节码必须有个一个关联的类加载器对象;

        生成的类中的方法的代码是怎样的,也得由我们提供。把我们的代码写在一个约定好了接口对象的方法中,把对象传给它,它调用我的方法,即相当于插入了我的代码。提供执行代码的对象就是那个InvocationHandler对象,它是在创建动态类的实例对象的构造方法时传递进去的。在上面的InvocationHandler对象的invoke方法中加一点代码,就可以看到这些代码被调用运行了。

     

       调用调用代理对象的从Object类继承的hashCode, equals, toString这几个方法时,代理对象将调用请求转发给InvocationHandler对象,对于其他方法,则不转发调用请求.

public class ProxyTest {
	public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Class clazzProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
		
		//打印所有的Proxy所有构造方法方法
		System.out.println("--------Proxy Constructoe List---------");
		Constructor[] constructors = clazzProxy.getConstructors();
		for(Constructor constructor : constructors) {
			StringBuilder strBui = new StringBuilder(constructor.getName());
			strBui.append('(');
			
			Class[] parameters1 = constructor.getParameterTypes();
			for(Class parameter : parameters1) {
				strBui.append(parameter.getName());
				strBui.append(',');
			}
			if(parameters1 != null && parameters1.length != 0) 
				strBui.deleteCharAt(strBui.length() - 1);
			strBui.append(')');
			
			System.out.println(strBui);
		}
			
		//打印 Proxy的所有方法
		System.out.println("-------Proxy Method List--------");
		Method[] methods = clazzProxy.getMethods();
		for(Method method : methods) {
			StringBuilder strBui = new StringBuilder(method.getName());
			strBui.append('(');
			
			Class[] methodParameters = method.getParameterTypes();
			for(Class parameter : methodParameters) {
				strBui.append(parameter.getName());
				strBui.append(',');
			}
			if(methodParameters != null && methodParameters.length != 0) 
				strBui.deleteCharAt(strBui.length() - 1);
			strBui.append(')');
			
			System.out.println(strBui);
		}
		
		//动态代理的三种写法
		//1.创建类实现接口
		class MyInvocationHandler implements InvocationHandler {
			@Override
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				// TODO Auto-generated method stub
				return null;
			}
		}
		MyInvocationHandler myInvocationHandler1 = new MyInvocationHandler(); 
		Constructor constructor = clazzProxy.getConstructor(InvocationHandler.class);
		Collection proxy1 = (Collection)constructor.newInstance(myInvocationHandler1);
		
		//2匿名类
		Collection proxy2 = (Collection)constructor.newInstance(new InvocationHandler(){
			@Override
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				// TODO Auto-generated method stub
				return null;
			}
		});
		
		//3可直接用Proxy中的静态方法直接动态类
		Collection proxy3 = (Collection) Proxy.newProxyInstance(
				Collection.class.getClassLoader(), 
				new Class[]{Collection.class}, 
				new InvocationHandler() {
					ArrayList arrayList = new ArrayList();
					//在每个动态类中的每个方法都会调用这个方法,只要有一个同样实现这个接口的类,就可以用这个Proxy调用实现了这个接口的对象,
					//其中proxy表示Proxy对象, mothod 是方法名 ,args是方法参数.
					//return会返回ArrList的相应方法的返回值并返回给Proxy的方法,并最终返回到我们调用的方法
					//在方法内可以对参数或方法,做一些过滤或改变
					public Object invoke(Object proxy, Method method, Object[] args)
							throws Throwable {
						long start = System.currentTimeMillis();
						Object obj = method.invoke(arrayList, args);
						long end = System.currentTimeMillis();
						System.out.println(method.getName() + "方法运行了" + (end - start) + "秒");
						return obj;
					}
				}
				);
		
		proxy3.add("lhm");
		proxy3.add("dfd");
		System.out.println(proxy3.size());
		
		
		//对于动态代理来说,关于Object基础的方法除了hashCode,equals,toString三个会有代理方法外,其他的方法都有自己的实现
		System.out.println(proxy3.getClass().getName());
	}
}


   创建代理方法

    该方法接口两个参数:一个是目标对象,另一个是封装了用户系统功能代码的Advice对象,该对象必须实现Advice接口。

public class ProxyTest2 {
	public static void main(String[] args) {
		final ArrayList arrayList = new ArrayList();
		Collection proxy3 = (Collection)getProxy(arrayList,new MyAdvice());
		proxy3.add("sdf");
		System.out.println(proxy3.size());
	}

	private static Object getProxy(final Object target, final Advice advice) {
		Object retval = Proxy.newProxyInstance(
			target.getClass().getClassLoader(), 
			target.getClass().getInterfaces(), 
			new InvocationHandler() {
				public Object invoke(Object proxy, Method method, Object[] args)
						throws Throwable {
					advice.before(method);
					Object obj = method.invoke(target, args);
					advice.after(method);
					return obj;
				}
			}
			);
		
		return retval;
	}
}


    Advice接口

public interface Advice {
	void before(Method method);
	void after(Method method);
}


     MaAdvice类

public class MyAdvice implements Advice{

	long start;
	long end;
	public void before(Method method) {
		start = System.currentTimeMillis();
		System.out.println("开始");
		
	}

	@Override
	public void after(Method method) {
		System.out.println("结束");
		end = System.currentTimeMillis();
		System.out.println(method.getName() + "共运行" + (end - start) + "秒");
	}

}


   实现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获取对象


     BeanFactory类

public class BeanFactory {
	
	Properties prop = new Properties();
	
	Object getBean(){
		Object bean = null;
		try {
			String className = prop.getProperty("xxx");
			Class clazz = Class.forName(className);
			bean = clazz.newInstance();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(bean instanceof ProxyFactoryBean) {
			ProxyFactoryBean proxyFactoryBean = (ProxyFactoryBean)bean;
			try {
				proxyFactoryBean.setAdvice((Advice)Class.forName(prop.getProperty("xxx.Advice")).newInstance());
				proxyFactoryBean.setTarget(Class.forName(prop.getProperty("xxx.Target")).newInstance());
			} catch (InstantiationException | IllegalAccessException
					| ClassNotFoundException e) {
				e.printStackTrace();
			}
			Object proxy = proxyFactoryBean.getProxy();
			return proxy;
		}
		
		return bean;
	}

	public BeanFactory(InputStream in) {
		try {
			prop.load(in);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


    PorxyFactoryBean类

public class ProxyFactoryBean {
	Object target = null;
	Advice advice = null;
	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;
	}
	Object getProxy() {
		Object retval = Proxy.newProxyInstance(
			target.getClass().getClassLoader(), 
			target.getClass().getInterfaces(), 
			new InvocationHandler() {
				public Object invoke(Object proxy, Method method, Object[] args)
						throws Throwable {
					advice.before(method);
					Object obj = method.invoke(target, args);
					advice.after(method);
					return obj;
				}
			}
			);
		
		return retval;
	}
}


   AopFrameworkTest类

public class AopFrameworkTest {
	public static void main(String[] args) {
		InputStream in = AopFrameworkTest.class.getResourceAsStream("config.Properties");
		Collection c = (Collection)new BeanFactory(in).getBean();
		c.add("Sd");
		System.out.println(c.getClass().getName());
	}
}

 

   config配置文件

xxx=java.util.ArrayList
#xxx=com.itheima.proxy.ProxyFactoryBean
xxx.Advice=com.itheima.proxy.MyAdvice
xxx.Target=java.util.ArrayList







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值