首先给出设计模式静态代理与动态代理的学习:
http://layznet.iteye.com/blog/1182924 讲的不错
然后我们实现AOP 就要求我们对委托的所有方法的调用实现拦截
代理类生成的工厂
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 |
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; } } |
测试:
1
2
3
4
5
6
7
8 |
public
class AOPTest { @Test public
void aopTest(){ ProxyFactory factory = new
ProxyFactory(); PersonService personService = (PersonService)factory.createProxyInstance( new
PersonServiceImpl( "xx" )); personService.save(); } } |
利用JDK的中Proxy动态代理实现Spring的AOP技术
原文:http://www.cnblogs.com/E-star/p/3560444.html