Spring底层AOP的实现原理

本文记录Java学习过程中遇到的Spring底层AOP的实现原理~

JDK动态代理

示例代码:

public class MyJDKProxy implements InvocationHandler {
	private UserDao userDao;

	public MyJDKProxy(UserDao userDao) {
		this.userDao = userDao;
	}

	//编写工具方法生成代理
	public UserDao createProxy() {
		UserDao userDaoProxy = (UserDao) Proxy.newProxyInstance(userDao.getClass().getClassLoader(), userDao.getClass(),getInterfaces(), this);
		return userDaoProxy;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		if ("save".equals(method.getName())) {
			System.out.println("权限校验");
		}
		return method.invoke(userDao, args);
	}
}

Cglib动态代理

示例代码:

public class MyCglibProxy implements MethodInterceptor {
	
	private CustomerDao customerDao;

	public MyCglibProxy(CustomerDao customerDao) {
		this.customerDao = customerDao;
	}

	// 生成代理的方法
	public CustomerDao createProxy() {

		// 创建Cglib的核心类
		Enhancer enhancer = new Enhancer();
		// 设置父类
		enhancer.setSuperclass(CustomerDao.class);
		// 设置回掉
		enhancer.setCallback(this);
		// 生成代理
		CustomerDao customerDaoProxy = (CustomerDao) enhancer.create();

		return customerDaoProxy;
	}

	@Override
	public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
		if ("delete".equals(method.getName())) {
			Object obj = methodProxy.invokeSuper(proxy, args);
			System.out.println("日志记录");
			return obj;
		}

		return methodProxy.invokeSuper(proxy, args);
	}
}

标签: none