动态代理类
/**
* @author 李亚杰
* @date 2024/4/7 10:57
* @description MyProxyUtil
*/
public class MyProxyUtil {
/**
* JDK动态代理
*
* @param t 需要被代理的对象
* @param <T>
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getProxyByJDK(@NotNull T t) {
return (T) Proxy.newProxyInstance(t.getClass().getClassLoader(),
t.getClass().getInterfaces(),
(proxy, method, args) -> method.invoke(t, args)
);
}
/**
*
* @param t 动态代理类
* @param before 前置通知方法
* @param after 后置通知方法
* @return
* @param <T>
*/
@SuppressWarnings("unchecked")
public static <T> T getProxyByCglib(@NotNull T t, Runnable before, Runnable after) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(t.getClass());
enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> {
before.run();
Object object = proxy.invokeSuper(obj, args);
after.run();
return object;
});
return (T) enhancer.create();
}
}
测试方法
@Test
public void test02(){
UserServiceImpl userService = new UserServiceImpl();
UserServiceImpl proxyByCglib = MyProxyUtil.getProxyByCglib(userService,
()-> System.out.println("前置通知"),
() -> System.out.println("后置通知")
);
proxyByCglib.insert(new User());
}
结果
也可以通过将函数式接口改为Function<T,R>的方式实现前置拦截。
代码如下
@SuppressWarnings("unchecked")
public static <T> T getProxyByCglib(@NotNull T t, Function<Object[],Boolean> before, Runnable after) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(t.getClass());
enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> {
if (!before.apply(args)) {
return null;
}
Object object = proxy.invokeSuper(obj, args);
after.run();
return object;
});
return (T) enhancer.create();
}
测试代码
@Test
public void test02() {
UserServiceImpl userService = new UserServiceImpl();
UserServiceImpl proxyByCglib = MyProxyUtil.getProxyByCglib(userService,
(args) -> {
System.out.println("前置拦截");
User user = (User) args[0];
return user != null;
},
() -> System.out.println("后置通知")
);
proxyByCglib.insert(null);
System.out.println("_________");
proxyByCglib.insert(new User());
}
测试结果
通过有返回值的函数实现了拦截效果