publicclassBookStoreImplimplementsIBookStore{ @Override publicvoidaddBook(){ // dosomething System.out.println("add a new book."); } }
定义业务代理类
1 2 3 4 5 6 7 8 9 10 11 12
publicclassBookStoreProxyimplementsIBookStore{ private BookStoreImpl bookStoreImpl; publicBookStoreProxy(BookStoreImpl bookStoreImpl){ this.bookStoreImpl = bookStoreImpl; } @Override publicvoidaddBook(){ // do more things before bookStoreImpl.addBook(); // do more things after } }
调用
1 2 3 4 5
publicstaticvoidmain(String[] args){ IBookStore bookstore = new BookStoreImpl(); BookStoreProxy proxy = new BookStoreProxy(bookstore); proxy.addBook(); }
// 包装调用方法:进行预处理/调用后处理 @Override public Object invoke(Object proxy, Method method, Object[] args)throws Throwable { Object result = null; // do more things before result = method.invoke(target, args); // do more things after return result; } }
调用
1 2 3 4 5 6
publicstaticvoidmain(String[] args){ BookStoreImpl bookStoreImpl = new BookStoreImpl(); BookProxy proxy = new BookProxy(); IBookStore bookStore = (IBookStore) proxy.bind(bookStoreImpl); bookStore.addBook(); }
@Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy)throws Throwable { // do more things before methodProxy.invokeSuper(o, objects); // 调用业务类(父类)的方法 // do more things after returnnull; } }
调用
1 2 3 4 5 6 7
publicstaticvoidmain(String[] args){ BookStoreImpl2 bookStore = new BookStoreImpl2(); BookCglib cglib = new BookCglib(); BookStoreImpl2 bookStoreCglib = (BookStoreImpl2)cglib.getInstance(bookStore); bookStoreCglib.addBook(); bookStoreCglib.delBook(); }