静态代理
public class Person {
public void eat(String name,String food){
System.out.println(name+"正在吃"+food+"!");
}
}
public class PersonProxy extends Person {
@Override
public void eat(String name, String food) {
System.out.println(name+"请先洗手!");
super.eat(name, food);
System.out.println("出门别忘带纸,防止拉肚子!");
}
}
测试类
public class TestPersonDaoDemo01 {
public static void main(String[] args) {
PersonProxy personProxy=new PersonProxy();
personProxy.eat("小明", "瓜");
}
}
CGLIB库动态代理
需要jar包spring-core-4.1.0.RC1.jar
public class Calculator {
public int add(int num1,int num2){
return num1+num2;
}
}
public class Person {
public void eat(String name,String food){
System.out.println(name+"正在吃"+food+"!");
}
}
代理工厂
public class ProxyFactory implements MethodInterceptor {
private Object target;
/**
* 根据传递的目标对象得到代理对象
* @param target
* @return
*/
public Object newProxyObject(Object target){
this.target=target;
//实例化用于生成代理对象的对象
Enhancer enhancer=new Enhancer();
//设置代理对象的父类对象的类模板对象
enhancer.setSuperclass(target.getClass());
//设置调用目标对象方法时关联的回调接口对象
enhancer.setCallback(this);
//调用enhancer的create()方法用于生成代理对象
Object proxy=enhancer.create();
return proxy;
}
/**
*
*/
@Override
public Object intercept(Object proxy, Method method, Object[] args,
MethodProxy methodProxy) throws Throwable {
System.out.println("数据校验");
Object returnValue=methodProxy.invoke(target, args);//调用目标对象的方法
System.out.println("returnValue="+returnValue);
System.out.println("日志记录");
return returnValue;
}
}
测试类
public class TestPersonDaoDemo01 {
public static void main(String[] args) {
/*//实例化代理工厂对象
ProxyFactory proxyFactory=new ProxyFactory();
//声明并实例化目标对象
Person person=new Person();
//通过给定目标对象生成代理对象
Person personProxy=(Person) proxyFactory.newProxyObject(person);
personProxy.eat("小明", "吃瓜");*/
ProxyFactory proxyFactory=new ProxyFactory();
Calculator calculator=(Calculator) proxyFactory.newProxyObject(new Calculator());
int sum=calculator.add(5,4);
System.out.println("sum="+sum);
}
}