Java的两种动态代理(基于JDK的动态代理+基于CGLIB的动态代理)
(这里直接上main方法,大家可以做一些结构化设计让代码使用效率更高)
一、基于JDK的动态代理
这里被代理对象是abcService
public static void main(String[] args) {
//目标对象--被代理对象
ABCService abcService=new ABCService();
//返回代理对象 调用JDK中Proxy类中的静态方法newProxyInstance获取动态代理类的实例
IService proxyService= (IService) Proxy.newProxyInstance(
abcService.getClass().getClassLoader(),
abcService.getClass().getInterfaces(),
new InvocationHandler() {
//回调函数 编写代理规则
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
System.out.println("开始事务");
Object invoke = method.invoke(abcService, args);//核心业务