java 代理機制的實例詳解
前言:
java代理分靜態代理和動態代理,動態代理有jdk代理和cglib代理兩種,在運行時生成新的子類class文件。本文主要練習下動態代理,代碼用于備忘。對于代理的原理和機制,網上有很多寫的很好的,就不班門弄斧了。
jdk代理
實例代碼
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
|
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ProxyFactory implements InvocationHandler { private Object tarjectObject; public Object creatProxyInstance(Object obj) { this .tarjectObject = obj; return Proxy.newProxyInstance( this .tarjectObject.getClass() .getClassLoader(), this .tarjectObject.getClass() .getInterfaces(), this ); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null ; if (AssessUtils.isAssess()) { result = method.invoke( this .tarjectObject, args); } else { throw new NoAssessException( "This server cannot run this service." ); } return result; } } |
cglib代理
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
|
import java.lang.reflect.Method; import org.springframework.cglib.proxy.Enhancer; import org.springframework.cglib.proxy.MethodInterceptor; import org.springframework.cglib.proxy.MethodProxy; public class ProxyCglibFactory implements MethodInterceptor { private Object tarjectObject; public Object creatProxyInstance(Object obj) { this .tarjectObject = obj; Enhancer enhancer= new Enhancer(); enhancer.setSuperclass( this .tarjectObject.getClass()); enhancer.setCallback( this ); return enhancer.create(); } @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy arg3) throws Throwable { Object result = null ; if (AssessUtils.isAssess()) { result = method.invoke( this .tarjectObject, args); } else { throw new NoAssessException( "This server cannot run this service." ); } return result; } } |
Aspect注解
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
30
|
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; @Aspect public class AssessInterceptor { @Pointcut (value= "execution (* com..*.*(..))" ) private void anyMethod(){}; @Before ( "anyMethod()" ) public void doBefore(JoinPoint joinPoint) throws NoAssessException{ if (!AssessUtils.isAssess()) { throw new NoAssessException( "This server cannot run this service." ); } } /** * Around異常的時候調用 * @param pjp * @throws Throwable */ @Around ( "anyMethod()" ) public void invoke(ProceedingJoinPoint pjp) throws Throwable{ pjp.proceed(); } } |
以上就是java代理機制的實例,如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://sheungxin.iteye.com/blog/2346329