当前位置: 代码迷 >> J2SE >> java动态署理
  详细解决方案

java动态署理

热度:12   发布时间:2016-04-24 00:44:12.0
java动态代理
对于静态代理我很理解了,但是动态代理还是不太懂,有人能举例说明下吗。一定要用例子,说的越详细越好。拜谢了

------解决方案--------------------
Java code
package com.design.proxy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class ProxySourceTest {    public static void main(String[] args) throws SecurityException,            NoSuchMethodException, Throwable {        ProxyTestInterface p = (ProxyTestInterface) MyInvocationHandler                .newProxy(new ProxyTestImpl());        /*         * byte[] b =         * ProxyGenerator.generateProxyClass("ProxyTestInterfaceProxy", new         * Class[] { p.getClass() });         *          * File file=newFile(         * "D:\\workspace8.5\\MTSJMS\\bin\\com\\design\\proxy\\ProxyTestInterfaceProxy.class"         * );         *          * FileOutputStream fos=new FileOutputStream(file); fos.write(b);         * fos.close();         */        System.out.println(p.hello("123"));    }}class MyInvocationHandler implements InvocationHandler {    private Object object;    public MyInvocationHandler(Object object) {        this.object = object;    }    public static Object newProxy(Object object) {        return Proxy.newProxyInstance(object.getClass().getClassLoader(),                object.getClass().getInterfaces(), new MyInvocationHandler(                        object));    }    public Object invoke(Object proxy, Method method, Object[] args)            throws Throwable {            System.out.println(method.invoke(object, args));        return "error";    }}
------解决方案--------------------
spring aop使用了代理模式,当目标对象是接口时作用JDK动态代理,普通类时则使用CGLIB代理
下面是JDK动态代理一个示例

public interface UserDao {
/**
* 切入点
*/
public void update();

public void delete();
}


public class UserDaoImpl implements UserDao {

public void delete(){
System.out.println("UserDao delete函数");
}

public void update(){
System.out.println("UserDao update函数");

}

}

public class UserInvocationHandler implements InvocationHandler {
private Object invocationObj;

public UserInvocationHandler(Object invocationObj) {
this.invocationObj = invocationObj;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
System.out.println("走JDK动态代理调用函数");// 此方法为:通知
Object obj = method.invoke(invocationObj, args);
return obj;
}

}

/**
 * JDK 动态代理
 * 
 */
public class App {
@Test
/**
* Aspect-Oriented Programming
*/
public void jdkProxy() {
UserDao dao = new UserDaoImpl();// dao为:目标对象
Object obj = Proxy.newProxyInstance(dao.getClass().getClassLoader(),
dao.getClass().getInterfaces(), new UserInvocationHandler(dao));
UserDao userdao = (UserDao) obj;
// 以下两个方法为:连接点
userdao.delete();
userdao.update();
}
}
------解决方案--------------------
一般永不到的 只是让你更了解spring 的 AOP
  相关解决方案