自己写的一个动态代理的小例子
package com.chinasoft.service;public interface UserService {public void add();}?
package com.chinasoft.service;public class UserServiceimpl implements UserService {public void add() {System.out.println("增加用户");}}?
public class ServiceProxy implements InvocationHandler{private Object obj;public ServiceProxy(Object obj) {super();this.obj = obj;}//这个方法用来获取代理对象public static Object getProxy(Object object){ Object ret= Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), new ServiceProxy(object)); return ret; }//因为实现InvocationHandler接口所以要去实现的方法,在这方法添加额外所需逻辑public Object invoke(Object proxy, Method method, Object[] args)throws Throwable { System.out.println("验证.........."); //在实际要操作的方法前添加所需逻辑 System.out.println("事务开始!!!!!!!!"); Object ob=method.invoke(obj, args); //obj是实际要操作的方法 System.out.println("事务结束!!!!!!!!"); //在实际要操作的方法后添加所需逻辑return ob;}}?
public class Test {/** * @param args */public static void main(String[] args) {UserServiceimpl ul=new UserServiceimpl(); //new出实际要去执行的类UserService us=(UserService) ServiceProxy.getProxy(ul);//把这对象传给代理us.add();}}?输出结果为:
验证..........事务开始!!!!!!!!增加用户事务结束!!!!!!!!
?