JDK動(dòng)態(tài)代理demo

1.JDK動(dòng)態(tài)代理

主要使用到?InvocationHandler?接口和?Proxy.newProxyInstance()?方法。?JDK動(dòng)態(tài)代理要求被代理實(shí)現(xiàn)一個(gè)接口,只有接口中的方法才能夠被代理?。其方法是將被代理對(duì)象注入到一個(gè)中間對(duì)象,而中間對(duì)象實(shí)現(xiàn)InvocationHandler接口,在實(shí)現(xiàn)該接口時(shí),可以在?被代理對(duì)象調(diào)用它的方法時(shí),在調(diào)用的前后插入一些代碼。而?Proxy.newProxyInstance()?能夠利用中間對(duì)象來生產(chǎn)代理對(duì)象。插入的代碼就是切面代碼。所以使用JDK動(dòng)態(tài)代理可以實(shí)現(xiàn)AOP。

下面來看例子

interface

public?interface?UserService?{

? ? void?addUser();

? ? String?findUserById();

}

impl

import?com.spring.aop.jdk.service.UserService;

public?class?UserServiceImpl?implements?UserService?{

? ? @Override

? ? public?void?addUser()?{

? ? ? ? System.out.println("start?insert?user?into?database");

? ? }

? ? @Override

? ? public?String?findUserById()?{

? ? ? ? System.out.println("start?find?user?by?userId");

? ? ? ? return?null;

? ? }

}

代理中間類

import java.lang.reflect.InvocationHandler;

import java.lang.reflect.Method;

public class ProxyUtil implements InvocationHandler {

? ? private Object target;//被代理的對(duì)象

? ? @Override

? ? public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

? ? ? ? System.out.println("do something before");

? ? ? ? // 調(diào)用被代理對(duì)象的方法并得到返回值

? ? ? ? Object result = method.invoke(target, args);

? ? ? ? System.out.println("do something after");

? ? ? ? return result;

? ? }

? ? public ProxyUtil(Object target) {

? ? ? ? this.target = target;

? ? }

? ? public Object getTarget() {

? ? ? ? return target;

? ? }

? ? public void setTarget(Object target) {

? ? ? ? this.target = target;

? ? }

}

Test

import java.lang.reflect.Proxy;

import com.spring.aop.jdk.proxy.ProxyUtil;

import com.spring.aop.jdk.service.UserService;

import com.spring.aop.jdk.service.impl.UserServiceImpl;

public class Main {

? ? public static void main(String[] args) {

? ? ? ? Object proxyObject = new UserServiceImpl();

? ? ? ? ProxyUtil proxyUtil = new ProxyUtil(proxyObject);

? ? ? ? UserService userService? = (UserService) Proxy.newProxyInstance(

? ? ? ? Thread.currentThread().getContextClassLoader(),

? ? ? ? UserServiceImpl.class.getInterfaces(), proxyUtil);

? ? ? ? userService.addUser();

? ? ? ? userService.findUserById();

? ? }

}


輸出結(jié)果

do something before

start insert user into database

do something after

do something before

start find user by userId

do something after

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容