通过JDK动态管理实现。
UserDao
package com.company.aop;
/**
* @author wyl
* @date 2021/3/5 20:20
*/
public interface UserDao {
public int add(int a, int b);
public int mul(int a, int b);
}
UserDaoimpl
package com.company.aop;
/**
* @author wyl
* @date 2021/3/5 20:21
*/
public class UserDaoimpl implements UserDao{
@Override
public int add(int a, int b) {
System.out.println("add is runing ...");
return a + b;
}
@Override
public int mul(int a, int b) {
System.out.println("mul is runing...");
return a * b;
}
}
JDKProxy
package com.company.aop;
import com.company.User;
import javafx.beans.InvalidationListener;
import org.springframework.cglib.proxy.Proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Array;
import java.util.Arrays;
/**
* @author wyl
* @date 2021/3/5 20:24
*/
public class JDkProxy {
public static void main(String[] args) {
Class [] interfaces = {UserDao.class};
UserDaoimpl userDaoimpl = new UserDaoimpl();
UserDao dao = (UserDao) Proxy.newProxyInstance(JDkProxy.class.getClassLoader(),interfaces,new UserDaoProxy(userDaoimpl));
int result = dao.add(1,1);
System.out.println("result:" + result);
}
}
class UserDaoProxy implements InvocationHandler, org.springframework.cglib.proxy.InvocationHandler {
private Object obj;
public UserDaoProxy(Object obj) {
this.obj = obj;
}
@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
System.out.println("方法之前执行...."+method.getName()+" :传递的参数..." + Arrays.toString(objects));
Object res = method.invoke(obj,objects);
System.out.println("方法之后执行..."+obj);
return res;
}
}
通过一步步的调试,可知先进入UserDaoProxy的invoke方法内,method.invoke是对上面的原方法进行调用,然后进行下面的操作。从而实现对方法的增强。
文章可能出现错误,希望大家提出自己的见解。