# 项目代码资源:
可能还在审核中,请等待。。。
https://download.csdn.net/download/chenhz2284/89457803
# 项目代码
【pom.xml】
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.3.0</version>
</dependency>
# 动态代理的例子
【BookFacade.java】
package com.chz.myProxy.dynamicProxy;
public interface BookFacade
{
void addBook();
}
【addBook.java】
package com.chz.myProxy.dynamicProxy;
public class BookFacadeImpl implements BookFacade
{
@Override
public void addBook() {
System.out.println("chz >>> addBook");
}
}
【BookFacadeProxy.java】
package com.chz.myProxy.dynamicProxy;
public class BookFacadeProxy implements InvocationHandler {
private Object target;
public Object bind(Object target) {
this.target = target;
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
Object result = null;
System.out.println("chz >>> dynamic proxy before: " + method.getName());
result = method.invoke(target, args);
System.out.println("chz >>> dynamic proxy after: " + method.getName());
return result;
}
}
【MyDynamicProxyTest.java】
package com.chz.myProxy.dynamicProxy;
@Slf4j
public class MyDynamicProxyTest
{
public static void main(String[] args)
{
BookFacadeProxy proxy = new BookFacadeProxy();
BookFacade bookProxy = (BookFacade)proxy.bind(new BookFacadeImpl());;
bookProxy.addBook();
}
}
运行【MyDynamicProxyTest】
# cglib代理的例子
【BookFacade.java】
package com.chz.myProxy.cglib;
public class BookFacade
{
public void addBook() {
System.out.println("chz >>> addBook");
}
}
【BookFacadeCglib.java】
package com.chz.myProxy.cglib;
public class BookFacadeCglib implements MethodInterceptor
{
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable
{
System.out.println("chz >>> cglib proxy before: " + method.getName());
proxy.invokeSuper(obj, args);
System.out.println("chz >>> cglib proxy after: " + method.getName());
return null;
}
}
【MyCglibProxyTest.java】
package com.chz.myProxy.cglib;
public class MyCglibProxyTest
{
public static void main(String[] args)
{
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(BookFacade.class); // 要代码的类
enhancer.setCallback(new BookFacadeCglib()); // 代理回调
BookFacade bookCglib = (BookFacade) enhancer.create(); // 创建一个代理对象
bookCglib.addBook(); // 使用代理对象
}
}
运行【MyCglibProxyTest】