本文主要是介绍黑马程序员---代理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
分析代理类的作用与原理及AOP的概念
代理的概念与作用
保持了原来那个类的功能,又增加了你现在需要的功能。
主函数调用的时候,直接调用代理类就行了。
这就是代理类的功能。
2.编写一个与目标类具有相同接口的代理类,代理类的每个方法调用目标类的相同方法,并在调用方法时加上系统功能的代码。
代理架构图:
AOP
1.系统中存在交叉业务,一个交叉业务就是要切入到系统中的一个方面,如下所示:
安全 事务 日志
StudentService ------|----------|------------|-------------
CourseService ------|----------|------------|-------------
MiscService ------|----------|------------|-------------
安全,事务,日志等功能要贯穿到好多个模块中,所以,它们就是交叉业务。
2.用具体的程序代码描述交叉业务:
method1 method2 method3
{ { {
------------------------------------------------------切面
.... .... ......
------------------------------------------------------切面
} } }
安全,事务,日志等这些功能,就是一个个的方面,不是一个点,而是一个面。是一个问题域。
------------------------------------------------------切面
func1 func2 func3
{ { {
.... .... ......
} } }
------------------------------------------------------切面
重要原则:不要把供货商暴露给你的客户。
动态代理技术
需要写一个示意代码进行辅助说明,例如:
Class proxy{
void sayHello(){
……….
try{
target.sayHello();
}catch(Exception e){
………..
}
………….
}
}
分析JVM动态生成的类
static Class<?> | getProxyClass(ClassLoader loader,Class<?>... interfaces) 返回代理类的 java.lang.Class 对象,并向其提供类加载器和接口数组。 |
package cn.itcast.day3;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collection;
public class ProxyTest {
public static void main(String[] args) {
//java.lang.reflect.Proxy类中的方法:
//static Class<?> getProxyClass(ClassLoader loader, Class<?>... interfaces)
//返回代理类的java.lang.Class对象,并向其提供类加载器和接口数组。
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)
{
StringBuilder sb = new StringBuilder();
sb.append(constructor.getName());
sb.append('(');
Class[] clazzParams = constructor.getParameterTypes();
if(clazzParams.length!=0 || clazzParams!=null)
{
for(Class clazzParam : clazzParams)
{
sb.append(clazzParam.getName()+',');
}
}
if(sb.charAt(sb.length()-1) != '(')
{
sb.deleteCharAt(sb.length()-1);
}
sb.append(')');
System.out.println(sb.toString());
}
System.out.println("----------------begin methods list--------------------");
Method[] methods = clazzProxy1.getMethods();
for(Method method : methods)
{
StringBuilder sb = new StringBuilder();
sb.append(method.getName());
sb.append('(');
Class[] clazzParams = method.getParameterTypes();
if(clazzParams.length!=0 || clazzParams!=null)
{
for(Class clazzParam : clazzParams)
{
sb.append(clazzParam.getName()+',');
}
}
if(sb.charAt(sb.length()-1) != '(')
{
sb.deleteCharAt(sb.length()-1);
}
sb.append(')');
System.out.println(sb.toString());
}
}
}
----------------begin constructors list--------------------
com.sun.proxy.$Proxy0(java.lang.reflect.InvocationHandler)
----------------begin methods list--------------------
add(java.lang.Object)
remove(java.lang.Object)
equals(java.lang.Object)
toString()
hashCode()
clear()
contains(java.lang.Object)
isEmpty()
size()
toArray()
toArray([Ljava.lang.Object;)
addAll(java.util.Collection)
iterator()
containsAll(java.util.Collection)
removeAll(java.util.Collection)
retainAll(java.util.Collection)
isProxyClass(java.lang.Class)
getInvocationHandler(java.lang.Object)
getProxyClass(java.lang.ClassLoader,[Ljava.lang.Class;)
newProxyInstance(java.lang.ClassLoader,[Ljava.lang.Class;,java.lang.reflect.InvocationHandler)
wait(long,int)
wait(long)
wait()
getClass()
notify()
notifyAll()
package cn.itcast.day3;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collection;
public class ProxyTest {
public static void main(String[] args) throws Exception{
Class clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
//既然是个类,那么肯定有构造方法或者方法
//首先看看这个类有什么构造方法:
System.out.println("----------------begin constructors list--------------------");
Constructor[] constructors = clazzProxy1.getConstructors();
for(Constructor constructor : constructors)
{
StringBuilder sb = new StringBuilder();
sb.append(constructor.getName());
sb.append('(');
Class[] clazzParams = constructor.getParameterTypes();
if(clazzParams.length!=0 || clazzParams!=null)
{
for(Class clazzParam : clazzParams)
{
sb.append(clazzParam.getName()+',');
}
}
if(sb.charAt(sb.length()-1) != '(')
{
sb.deleteCharAt(sb.length()-1);
}
sb.append(')');
System.out.println(sb.toString());
}
System.out.println("----------------begin create instance object--------------------");
//Object obj = clazzProxy1.newInstance();//调用空参构造方法,可是我们从上面看到此类没有空参构造,所以报异常。
Constructor constructor = clazzProxy1.getConstructor(InvocationHandler.class);
class MyInvocationHandler1 implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
return null;
}
}
Collection proxy1 = (Collection)constructor.newInstance(new MyInvocationHandler1());
System.out.println(proxy1.toString());
//proxy1.size();//有返回值的方法不能调用,会报异常,这是为什么呢?
proxy1.clear();
}
}
Ø 将创建动态类的实例对象的代理改成匿名内部类的形式编写,锻炼大家习惯匿名内部类。
package cn.itcast.day3;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collection;
public class ProxyTest {
public static void main(String[] args) throws Exception{
Class clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
System.out.println("----------------begin create instance object--------------------");
Constructor constructor = clazzProxy1.getConstructor(InvocationHandler.class);
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;
}
});
System.out.println(proxy2.toString());
}
}
5.总结思考:让jvm创建动态类及其实例对象,需要给它提供哪些信息?
Foo
的代理:
static Object | newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h) 这里的参数不能用可变参数!返回一个指定接口的代理类实例,该接口可以将方法调用指派到指定的调用处理程序。 |
package cn.itcast.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 {
public static void main(String[] args) throws Exception{
//java.lang.reflect.Proxy类中的方法:
//static Class<?> getProxyClass(ClassLoader loader, Class<?>... interfaces)
//返回代理类的java.lang.Class对象,并向其提供类加载器和接口数组。
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)
{
StringBuilder sb = new StringBuilder();
sb.append(constructor.getName());
sb.append('(');
Class[] clazzParams = constructor.getParameterTypes();
if(clazzParams.length!=0 || clazzParams!=null)
{
for(Class clazzParam : clazzParams)
{
sb.append(clazzParam.getName()+',');
}
}
if(sb.charAt(sb.length()-1) != '(')
{
sb.deleteCharAt(sb.length()-1);
}
sb.append(')');
System.out.println(sb.toString());
}
System.out.println("----------------begin methods list--------------------");
Method[] methods = clazzProxy1.getMethods();
for(Method method : methods)
{
StringBuilder sb = new StringBuilder();
sb.append(method.getName());
sb.append('(');
Class[] clazzParams = method.getParameterTypes();
if(clazzParams.length!=0 || clazzParams!=null)
{
for(Class clazzParam : clazzParams)
{
sb.append(clazzParam.getName()+',');
}
}
if(sb.charAt(sb.length()-1) != '(')
{
sb.deleteCharAt(sb.length()-1);
}
sb.append(')');
System.out.println(sb.toString());
}
System.out.println("----------------begin create instance object--------------------");
//Object obj = clazzProxy1.newInstance();//调用空参构造方法,可是我们从上面看到此类没有空参构造,所以报异常。
Constructor constructor = clazzProxy1.getConstructor(InvocationHandler.class);
class MyInvocationHandler1 implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
return null;
}
}
Collection proxy1 = (Collection)constructor.newInstance(new MyInvocationHandler1());
System.out.println(proxy1.toString());
//proxy1.size();//有返回值的方法不能调用,会报异常,这是为什么呢?
proxy1.clear();
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;
}
});
System.out.println(proxy2.toString());
Collection proxy3 = (Collection)Proxy.newProxyInstance(
Collection.class.getClassLoader(),
new Class[] {Collection.class},
new InvocationHandler() {
ArrayList target = new ArrayList();
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
long beginTime = System.currentTimeMillis();
Object retVal = method.invoke(target, args);
long endTime = System.currentTimeMillis();
System.out.println(method.getName()+" running time of "+(endTime-beginTime));
return retVal;
}
});
proxy3.add("zxx");
proxy3.add("lxx");
proxy3.add("yxx");
System.out.println(proxy3.size());
}
}
运行结果:
add running time of 0
add running time of 0
add running time of 0
size running time of 1
3
猜想分析动态生成的类的内部代码
$Proxy0 implements Collection
{
InvocationHandler handler;
public $Proxy0(InvocationHandler handler)
{
this.handler = handler;
}
}
$Proxy0 implements Collection
{
InvocationHandler handler;
public $Proxy0(InvocationHandler handler)
{
this.handler = handler;
}
//生成的Collection接口中的方法的运行原理
int size()
{
return handler.invoke(this,this.getClass().getMethod("size"),null);
}
void clear(){
return handler.invoke(this,this.getClass().getMethod("clear"),null);
}
boolean add(Object obj){
return handler.invoke(this,this.getClass().getMethod("add"),obj);
}
}
Class Proxy$ {
add(Object object) {
return handler.invoke(Object proxy, Method method, Object[] args);
}
}
4.分析先前打印动态类的实例对象时,结果为什么会是null呢?调用有基本类型返回值的方法时为什么会出现NullPointerException异常?
让动态生成的类成为目标类的代理
1.分析动态代理的工作原理图:
接口Advice.java:
package cn.itcast.day3;
import java.lang.reflect.Method;
public interface Advice {
void beforeMethod(Method method);
void afterMethod(Method method);
}
MyAdvice.java:
package cn.itcast.day3;
import java.lang.reflect.Method;
public class MyAdvice implements Advice {
long beginTime = 0;
@Override
public void beforeMethod(Method method) {
System.out.println("来传智播客学习了");
beginTime = System.currentTimeMillis();
}
@Override
public void afterMethod(Method method) {
System.out.println("从传智播客毕业上班啦");
long endTime = System.currentTimeMillis();
System.out.println(method.getName()+" running time of "+(endTime-beginTime));
}
}
ProxyTest.java:
package cn.itcast.day3;
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 {
public static void main(String[] args) throws Exception{
final ArrayList target = new ArrayList();//内部类里想访问局部变量,加final修饰符。
Collection proxy3 = (Collection)getProxy(target,new MyAdvice());
proxy3.add("zxx");
proxy3.add("lxx");
proxy3.add("yxx");
System.out.println(proxy3.size());
}
private static Object getProxy(final Object target, final Advice advice) {
Object proxy3 = Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
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 proxy3;
}
}
实现类似spring的可配置的AOP框架
实现AOP功能的封装与配置
#xxx=java.util.ArrayList
xxx=cn.itcast.ProxyFactoryBean
xxx.target=java.util.ArrayList
xxx.advice=cn.itcast.MyAdvice
Advice.java:
package cn.itcast.day3;
import java.lang.reflect.Method;
public interface Advice {
void beforeMethod(Method method);
void afterMethod(Method method);
}
MyAdvice.java:
package cn.itcast.day3;
import java.lang.reflect.Method;
public class MyAdvice implements Advice {
long beginTime = 0;
@Override
public void beforeMethod(Method method) {
System.out.println("来传智播客学习了");
beginTime = System.currentTimeMillis();
}
@Override
public void afterMethod(Method method) {
System.out.println("从传智播客毕业上班啦");
long endTime = System.currentTimeMillis();
System.out.println(method.getName()+" running time of "+(endTime-beginTime));
}
}
BeanFactory.java:
package cn.itcast.day3.aopframework;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import cn.itcast.day3.Advice;
public class BeanFactory {
Properties props = new Properties();
public BeanFactory(InputStream ips) {
try {
props.load(ips);
} catch (IOException e) {
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) {
e.printStackTrace();
}
if(bean instanceof ProxyFactoryBean)
{
ProxyFactoryBean proxyFactoryBean = (ProxyFactoryBean)bean;
Object target = null;
Advice advice = null;;
try {
target = Class.forName(props.getProperty(name+".target")).newInstance();
advice = (Advice)Class.forName(props.getProperty(name+".advice")).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
proxyFactoryBean.setTarget(target);
proxyFactoryBean.setAdvice(advice);
Object proxy = ((ProxyFactoryBean)bean).getProxy();
return proxy;
}
return bean;
}
}
ProxyFactoryBean.java:
package cn.itcast.day3.aopframework;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import cn.itcast.day3.Advice;
public class ProxyFactoryBean {
private Object target;
private Advice advice;
public Object getTarget() {
return target;
}
public void setTarget(Object target) {
this.target = target;
}
public Advice getAdvice() {
return advice;
}
public void setAdvice(Advice advice) {
this.advice = advice;
}
public Object getProxy() {
Object proxy3 = Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
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 proxy3;
}
}
AopFrameworkTest.java:
package cn.itcast.day3.aopframework;
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());
}
}
这篇关于黑马程序员---代理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!