一、静态代理
代理对象和被代理对象必须实现同一个接口,在代理对象中只需要关注切入点的横向业务,在需要的时候调用被代理对象
优点:在代理业务中只保留相关业务
缺点:一个代理对象只能实现一个代理对象,当需要代理的对象很多时候,无法满足
step1:定义一个接口
//1.定义一个接口
interface IHello{
void sayHi(String content);
}
step2:定义实现类
//2.编写业务逻辑类实现接口并实现接口中的方法
public class HelloSpeaker implements IHello{
public void sayHi(String content){}
}
step3:定义一个代理类
//3.编写代理类实现接口并实现接口中的方法,并将日志服务添加到代理对象中。
public class HelloProxy implements IHello{
private IHello target;//被代理对象
public void sayHi(String content){
//日志服务
//业务逻辑
target.sayHi(content);
//日志服务
}
public HelloProxy(IHello target){
this.target = target;
}
}
step4:测试
//4.编写测试类测试功能实现
public static void main(String[] args){
IHello proxy = new HelloProxy(new HelloSpeaker());
proxy.sayHi("hello");
}
二、动态代理
处理者必须实现java.lang.reflect.InvocationHandler接口
step1、step2同上
step3:一个代理类实现InvocationHandler接口
public class LogHandler implements InvocationHandler {
private Object targetObject;//代理的目标对象
public Object createProxyInstance(Object targetObject){
this.targetObject = targetObject;
/*
* 第一个参数设置代码使用的类装载器,一般采用跟目标类相同的类装载器
* 第二个参数设置代理类实现的接口
* 第三个参数设置回调对象,当代理对象的方法被调用时,会委派给该参数指定对象的invoke方法
*/
return Proxy.newProxyInstance(this.targetObject.getClass().getClassLoader(),
this.targetObject.getClass().getInterfaces(), this);
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
//日志服务
//业务操作
result = method.invoke(this.targetObject, args);//把方法调用委派给目标对象
//日志服务
return result;
}
}
step4:在xxx.xml配置参数
<bean id="helloSpeaker" class="com.woniuxy.proxy.HelloSpeaker"/>
<bean id="logHandler" class="com.woniuxy.proxy.LogHandler">
<property name="target" ref="helloSpeaker"/>
</bean>
step5:编写测试类
public static void main(String[] args){
LogHandler logHandler = new LogHandler();
IHello proxy = (IHello)logHandler.createProxyInstance(new HelloSpeaker());
proxy.sayHi("Hello");
}