动态代理:可以在程序的执行过程中创建代理对象
通过代理对象执行方法,给目标类的方法增加额外的功能(功能增强)
jdk动态代理实现步骤:
1.创建目标类,SomeServiceImpl目标类,给doSome(), doOther()增加输出时间、事务
2.创建InvocationHandler接口的实现类,在这个类实现给目标方法增加功能
3.使用jdk中类proxy创建代理对象,实现创建对象的能力
public interface SomeService {
void doSome();
void doOther();
}
public class SomeServiceImpl implements SomeService {
@Override
public void doSome() {
System.out.println("执行业务方法doSome");
}
@Override
public void doOther() {
System.out.println("执行业务方法doOther");
}
}
public class ServiceTools {
public static void doLog() {
System.out.println("非业务方法,方法的执行时间:" + new Date());
}
public static void doTrans() {
System.out.println("方法执行完毕后,提交事务");
}
}
public class MyInvocationHandler implements InvocationHandler {
// 目标对象
private Object target; // SomeServiceImpl类
public MyInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 通过代理对象执行方法时,会调用invoke()方法
System.out.println("执行了MyInvocationHandler中的invoke()");
Object res = null;
if ("doSome".equals(method.getName())) {
ServiceTools.doLog();
// 执行目标类的方法,通过Method类实现
res = method.invoke(target,args);// SomeServiceImpl.doSome()、或SomeServiceImpl.doOther()
ServiceTools.doTrans();
} else {
res = method.invoke(target,args);
}
// 目标方法的执行结果
return res;
}
}
public class MyApp {
public static void main(String[] args) {
// 调用 doSome、doOther
/*
SomeService service = new SomeServiceImpl();
service.doSome();
System.out.println("++++++++++++++++++++++");
service.doOther();
*/
// 使用jdk中类proxy创建代理对象
// 创建目标对象
SomeService target = new SomeServiceImpl();
// 创建InvocationHandler对象
InvocationHandler handler = new MyInvocationHandler(target);
// 使用proxy创建代理
SomeService proxy = (SomeService) Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(),handler);
// 通过代理执行方法,会调用handler中的invoke()
proxy.doSome();
}
}