AOP jdk动态代理

一:

   jdk动态代理是Spring AOP默认的代理方法。要求 被代理类要实现接口,只有接口里的方法才能被代理,主要步骤是先创建接口,接口里创建要被代理的方法,然后定义一个实现类实现该接口,接着将被代理对象注入到一个中间对象,中间对象实现InvocationHandler接口,实现该接口可以在 被代理对象调用它的方法前后插入一些代码。Proxy.newProxyInstance()能利用中间对象来生产代理对象。

二:

(1)创建接口:

package net.wang.aop;

/**
 * 被代理对象必须实现的接口
 * @author LiuRuoWang
 */
public interface UserService {
	
	public void addUser(User user);
	
	public User getUser(int id);
}

(2)创建实现类:

package net.wang.aop;

/**
 * 被代理对象,必须实现接口
 * @author LiuRuoWang
 */
public class UserServiceImpl implements UserService{

	public void addUser(User user) {
		System.out.println("add User!");
	}

	public User getUser(int id) {
		User user=new User();
		user.setId(id);
		System.out.println("get User!");
		return user;
	}
	
}

(3)创建代理中间类

package net.wang.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 代理中间类
 * @author LiuRuoWang
 */
public class ProxyUtil implements InvocationHandler{
	
	//被代理对象
	private Object target;
	
	public void setTarget(Object target) {
		this.target = target;
	}
	
	public Object getTarget() {
		return target;
	}
	
	public ProxyUtil(Object target){
		this.target=target;
	}
	
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		System.out.println("do sth before!");
		method.invoke(target, args);
		System.out.println("do sth after!");
		return null;
	}
	
	
}

(4)pojo类:

package net.wang.aop;

/**
 * User pojo类
 * @author LiuRuoWang
 */
public class User {
	
	private Integer id;
	
	private String name;
	
	public void setId(Integer id) {
		this.id = id;
	}
	
	public Integer getId() {
		return id;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public String getName() {
		return name;
	}
}

(5)测试结果

package net.wang.aop;

import java.lang.reflect.Proxy;

public class ProxyTest {
	
	public static void main(String[] args) {
		
		Object proxyedObject = new UserServiceImpl();
		
		ProxyUtil proxyUtils = new ProxyUtil(proxyedObject);
		//生成代理对象,并对这些接口进行代理
		UserService proxyObject = (UserService) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), 
				UserServiceImpl.class.getInterfaces(),proxyUtils);
		proxyObject.getUser(1);
		proxyObject.addUser(new User()); 
	}
}

(6)

image

原文地址:https://www.cnblogs.com/liuruowang/p/4544710.html