利用动态代理给方法增加功能
动态代理:可以在程序执行的过程中,创建代理对象。
通过代理对象执行方法,给目标类的方法增加额外的功能(功能增强)。动态代理实现代码的解耦合。
jdk动态代理实现步骤:
1、创建目标类,SomeServiceImpl目标类,给它的doSome,doOther方法增加输出时间,事务的功能。
2、创建InvocationHandler接口的实现类,在这个类实现给目标方法增加功能。
3、使用jdk中 类Proxy,创建代理对象,实现创建对象的能力。
public interface SomeService {
void doSome();
void doOther();
}
public class SomeServiceImpl implements SomeService{
public void doSome(){
System.out.println("doSome");
}
public void doOther(){
System.out.println("doOther");
}
}
public class MyIncationHandler implements InvocationHandler {
private Object target;
public MyIncationHandler(Object target){
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//调用时间方法
System.out.println("Time");
Object res = method.invoke(target, args);
//调用事务方法
System.out.println("Do...");
return res;
}
}
public class MyApp {
public static void main(String[] args) {
SomeService someService = new SomeServiceImpl();
InvocationHandler invocationHandler = new MyIncationHandler(someService);
SomeService o =(SomeService) Proxy.newProxyInstance(someService.getClass().getClassLoader(), someService.getClass().getInterfaces(), invocationHandler);
o.doSome();
}
}
注意:使用Proxy只能生成接口,不能是类 ,newProxyInstance方法中前两个为目标类的加载器和接口。