动态代理

动态代理是springaop中底层的实现,主要实现方法就是实现了InvocationHandler接口,并实现invoke方法,

下面是作者写的测试代码,仅供参考。

 

接口UserService

public interface UserService {

	void add();

	int delete(String id);

	int update(String id, String name, String age);

	int insert(String id, String name, String age);
}

实现类UserServiceImpl

public class UserServiceImpl implements UserService {

	@Override
	public void add() {
		System.out.println("add个啥,你啥也没传");
	}

	@Override
	public int delete(String id) {
		System.out.println("id:"+id+"被删除了");
		return 0;
	}

	@Override
	public int update(String id, String name, String age) {
		System.out.println("id:"+id+"修改成功[name:"+name+"age:"+age+"]");
		return 1;
	}

	@Override
	public int insert(String id, String name, String age) {
		System.out.println("插入成功[id:"+id+"name:"+name+"age:"+age+"]");
		return 2;
	}

}

代理实现类ProxyTest

public class ProxyTest implements InvocationHandler {

	private Object target;

	public ProxyTest(Object object) {
		super();
		this.target = object;
	}

	public Object getTarget() {
		return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

		//打印参数
		System.out.println(Arrays.toString(args));
		if (method.getName().equals("update")) {
			System.out.println("update不让--**");
			return 0;
		}

		System.out.println("--->方法要执行了,各部门就位<---");
		Object invoke = method.invoke(target, args);
		System.out.println("--->完事了,散了吧<---");
		return invoke;
	}

}

测试类MainTest

public class MainTest {

	public static void main(String[] args) {

		UserService userservice = new UserServiceImpl();
		ProxyTest proxytest = new ProxyTest(userservice);
		UserService proxy = (UserService)proxytest.getTarget();
		proxy.add();
		System.out.println(proxy.delete("15"));
		System.out.println(proxy.insert("20","张三丰","99"));
		System.out.println(proxy.update("20","张君宝","25"));
	}

}

 

你可能感兴趣的:(Java设计模式,设计模式,jdk动态代理)