\(^_^)/ JDK动态代理模拟Spring的AOP

参考:http://dyygusi.iteye.com/blog/1997231

参考:http://550516671-qq-com.iteye.com/blog/833816

 

 

 

代理类:

package spring.mock;

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

public class MockSpringAOP implements InvocationHandler {
	private Object target;

	public MockSpringAOP(Object obj) {
		this.target = obj;
	}

	public void setTarget(Object target) {
		this.target = target;
	}

	public void before() {
		System.out.println("这是一个前置通知");
	}

	public void afterReturning() {
		System.out.println("这是一个后置通知");
	}

	public void afterThrowing() {
		System.out.println("这是一个异常通知");
	}

	public void after() {
		System.out.println("这是一个最终通知");
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Object returnVal = null;
		try {
			before();
			returnVal = method.invoke(target, args);
			afterReturning();
		} catch (Exception e) {
			afterThrowing();
		} finally {
			after();
		}
		return returnVal;
	}

}

 

 

 

代理对象

package spring.mock;
public class User {
    Integer id;
    String name;
    String pwd;
    public User() {
    }

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }
}






package spring.mock;

public interface UserDAO {
	public void addUser(User user);
}







package spring.mock;

public class UserDAOImpl implements UserDAO {

	@Override
	public void addUser(User user) {
		System.out.println("保存User到数据库中");
		throw new RuntimeException();
	}

}

 

 

 

测试

package spring.mock;

import java.lang.reflect.Proxy;

public class Test {
	public static void main(String[] args) {

		UserDAO userDao = new UserDAOImpl();
		MockSpringAOP interceptor = new MockSpringAOP(userDao);
		// 通过代理的静态方法创建一个代理对象
		// 这个代理创建的时候,接收了接口类型和拦截器的处理类,在代理的背后,他会调运拦截器的invoke这个方法。
		// 因为传递的有接口类型,所以可以强制类型转换到我们指定的接口类型
		UserDAO userDaoProxy = (UserDAO) Proxy.newProxyInstance(interceptor.getClass().getClassLoader(), userDao.getClass().getInterfaces(), interceptor);
		// 然后在代理对象处理的时候,就会将我的逻辑织如到被代理的对象上
		userDaoProxy.addUser(new User(1, "a", "b"));
	}
}

 

 

 

你可能感兴趣的:(JDK动态代理)