java 代理機制的實例詳解
前言:
java代理分靜態代理和動態代理,動態代理有jdk代理和cglib代理兩種,在運行時生成新的子類class文件。本文主要練習下動態代理,代碼用于備忘。對于代理的原理和機制,網上有很多寫的很好的,就不班門弄斧了。
jdk代理
實例代碼
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異常的時候調用 * @param pjp * @throws Throwable */ @Around("anyMethod()") public void invoke(ProceedingJoinPoint pjp) throws Throwable{ pjp.proceed(); } }
以上就是java代理機制的實例,如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。