利用JDK的中Proxy动态代理实现Spring的AOP技术

首先给出设计模式静态代理与动态代理的学习:

http://layznet.iteye.com/blog/1182924   讲的不错

 

然后我们实现AOP 就要求我们对委托的所有方法的调用实现拦截

 

代理类生成的工厂

 

package cn.gbx.aop;

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

import cn.gbx.service.impl.PersonService;

public class ProxyFactory implements InvocationHandler{
	private Object targetObject;
	
	public Object createProxyInstance(Object targetObject) {
		this.targetObject = targetObject;
		return Proxy.newProxyInstance(this.targetObject.getClass().getClassLoader(),
				this.targetObject.getClass().getInterfaces(), 
				this);
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		PersonService service = (PersonService) this.targetObject;
		Object result = null;
		if (service.getUser() != null) {
			result = method.invoke(this.targetObject, args);
		}
		return result;
	}
}

  

测试:

public class AOPTest {
	@Test
	public void aopTest(){
		ProxyFactory factory = new ProxyFactory();
		PersonService personService = (PersonService)factory.createProxyInstance(new PersonServiceImpl("xx"));
		personService.save();
	}
}

  

 

posted @ 2014-02-22 09:54  E_star  阅读(361)  评论(0编辑  收藏  举报