前言
例如:
假设对于一个类,有方法sayHello
@Component
public class Hello implements HelloInterface{
@Value("cjl")
private String name;
public void setName(String name) {
this.name = name;
}
public void sayHello(){
System.out.println("pasaki");
}
}
通常如果想在某方法执行前后增加功能,我们会在类的原代码前后增加功能
public void sayHello(){
System.out.println("执行前增加的功能");
System.out.println("pasaki");
System.out.println("执行后增加的功能");
}
在此基础上要优化代码,可以把增加的功能提取出来变成一个功能类
package org.example;
public class Utils {
public static void before(){
System.out.println("执行前增加的功能");
}
public static void after(){
System.out.println("执行后增加的功能");
}
}
那么在原来的Hello中就可以使用
public void sayHello(){
Utils.before();
System.out.println("pasaki");
Utils.after();
}
这种方法虽然结构上清晰了不少,但是我们的Hello类就不能专注自己的业务逻辑,如果要修改增加的功能,我们改了Utils类之后还需要回到Hello类就去修改,如果我们需要Utils和Hello只专注与自己的方法
这个时候我们就需要动态代理。在不修改原有代码的情况下增加功能
动态代理
在程序执行过程中,创建代理对象,通过代理对象执行方法,给目标类的方法增加额外的功能(功能增强)
JDK动态代理的实现步骤
- 创建目标类,Hello的目标类,给它的sayHello方法增加功能
- 创建InvocationHandler接口的实现类,在这个类是献给目标方法增加功能
- 使用jdk中的类Proxy,创建代理对象。实现创建对象的能力
创建InvocationHandler的实现类
package org.example;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
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 {
//通过代理对象执行方法时,会调用执行这个invoke()
Object res=null;
if(method.getName().equals("sayHello")){
Utils.before();
//执行目标类的方法
res=method.invoke(target,args);
Utils.after();
//目标方法的执行结果
}else{
res=method.invoke(target,args);
}
//目标方法的执行结果
return res;
}
}
测试实现
@Test
public void shouldAnswerWithTrue()
{
//1、指定spring配置文件的名称
String config="spring_total" + ".xml";
//2、创建表示spring容器的对象,ApplicationContext
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config);
//3、通过容器获取对象
Hello hello = (Hello) context.getBean("hello");
MyIncationHandler handler = new MyIncationHandler(hello);
HelloInterface proxy = (HelloInterface) Proxy.newProxyInstance(hello.getClass().getClassLoader(), hello.getClass().getInterfaces(), handler);
proxy.sayHello();
}
通过动态代理,实现了业务逻辑和增强逻辑的分离,保持了功能的独立性。