强烈推荐一个大神的人工智能的教程:
简述 |
为什么要使用代理 |
####2.1未使用代理时
public class BookService{public void hello(){System.out.println("方法之前...");System.out.println("我是service");}
}
在这个功能上又来了新需求:在这个方法后打印"方法之后…"这几个字,这时候又需要修改现有的代码
缺点:
####2.2 使用静态代理优化
①定义一个抽象接口:
public interface IBookService {public void hello();
}
②被代理类实现IBookService接口:
public class BookService implements IBookService{public void hello(){System.out.println("我是service");}
}
③创建一个代理类,实现共同的接口IBookService
public class Proxy implements IBookService {//依赖被代理的对象IBookService bookService = new BookService();//重写方法public void hello() {System.out.println("方法之前...");//调用被代理对象的接口bookService.hello();}
}
优点:
缺点:
public class Proxy implements InvocationHandler {Object targetObject;//3.创建一个方法来生成对象,参数是要代理的对象,getInstance返回的对象是代理对象public Object getInstance(Object o){//3.1创建LogProxy对象//3.2设置这个代理对象this.targetObject = o;//3.3通过Proxy的方法创建代理对象,第一个参数是要代理对象的classLoader//第二个参数是要代理对象实现的所有接口,第三个参数是实现类的InvocationHandler对象//此时的result就是一个代理对象,代理的是oObject result = Class().getClassLoader(),o.getClass().getInterfaces(),this);return result;}public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("方法之前...");Object invoke = method.invoke(targetObject, args);return invoke;}
}
写一个测试类:
public class TestJDK {public static void main(String[] args) {IBookService instance = (IBookService) new Proxy().getInstance(new BookService());instance.hello();}
}
执行结果:
方法之前...
我是service
总结:
<dependency><groupId>cglib</groupId><artifactId>cglib</artifactId><version>3.1</version>
</dependency>
②代理类:
public class Proxy implements MethodInterceptor Enhancer enchancer = new Enhancer();//字节码增强器public Object getInstance(Object o){enchancer.setSuperclass(User.class);//设置被代理类为父类enchancer.setCallback(new UserInterceptor());//设置回调ate();//创建代理实例}public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {System.out.println("方法之前...");Object object = methodProxy.invokeSuper(o,objects);return object;}}
③写一个测试类:
public class TestCglib {public static void main(String[] args) {BookService instance = (BookService) new Proxy().getInstance(new BookService());instance.hello();}
}
总结:
总结 |
本文发布于:2024-01-31 22:46:05,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170671236631932.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |