AOP(JDK動態代理)
阿新 • • 發佈:2021-02-01
-
使用JDK動態代理,使用Proxy類中的方法建立代理物件
(1)呼叫newProxyInstance方法方法中有三個引數引數一:ClassLoader(類載入器)
引數二:增強方法所在類,類實現的介面,支援多個介面
引數三:實現這個介面InvocationHandler,建立代理物件,寫增強的方法 -
JDK動態代理程式碼
package com.yang.run;
import com.yang.dao.UserDao;
import com.yang.dao.impl.UserImplDao;
import org. junit.Test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @program: TestSpring
* @description: 測試JDK動態代理
* @author: 陳陽
* @create: 2021-01-30 20:37
**/
public class TestProxy {
@Test
public void test1(){
Class [] inter = {UserDao.class};
/**
* 引數一:當前類
* 引數二:增強類的陣列
* 引數三: 實現InvocationHandler的類
*/
// Proxy.newProxyInstance(TestProxy.class.getClassLoader(), inter, new InvocationHandler() {
// public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// return null;
// }
// });
UserDao uDao = (UserDao)Proxy.newProxyInstance(TestProxy.class.getClassLoader(), inter, new UserDaoProxy1(new UserImplDao()));
int add = uDao.add(1, 2);
System.out.println(add);
}
class UserDaoProxy1 implements InvocationHandler{
//把被代理物件傳到代理類中
private Object obj;
//設定有參構造
public UserDaoProxy1(Object obj) {
this.obj=obj;
}
/**
* 增強方法
* @param proxy
* @param method
* @param args
* @return
* @throws Throwable
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("執行前程式碼");
//返回方法名
String name = method.getName();
//被增強方法執行
Object invoke = method.invoke(obj, args);
System.out.println("執行後代碼");
return invoke;
}
}