java 代理機(jī)制的實(shí)例詳解
為廣陵等地區(qū)用戶提供了全套網(wǎng)頁(yè)設(shè)計(jì)制作服務(wù),及廣陵網(wǎng)站建設(shè)行業(yè)解決方案。主營(yíng)業(yè)務(wù)為網(wǎng)站制作、做網(wǎng)站、廣陵網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠(chéng)的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長(zhǎng)期合作。這樣,我們也可以走得更遠(yuǎn)!
前言:
java代理分靜態(tài)代理和動(dòng)態(tài)代理,動(dòng)態(tài)代理有jdk代理和cglib代理兩種,在運(yùn)行時(shí)生成新的子類class文件。本文主要練習(xí)下動(dòng)態(tài)代理,代碼用于備忘。對(duì)于代理的原理和機(jī)制,網(wǎng)上有很多寫的很好的,就不班門弄斧了。
jdk代理
實(shí)例代碼
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代理
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注解
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異常的時(shí)候調(diào)用 * @param pjp * @throws Throwable */ @Around("anyMethod()") public void invoke(ProceedingJoinPoint pjp) throws Throwable{ pjp.proceed(); } }
以上就是java代理機(jī)制的實(shí)例,如有疑問(wèn)請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!