spring AOP 的实现是基于java的动态代理,其目的就是不改写原来代码来添加功能:
代理接口:
public interface User {
public void save();
public void test();
}
实现类:
public class UserImpl implements User {
public void save(){
System.out.println("Method save invoke!!!");
}
public void test(){
System.out.println("test method!!!1");
}
}
代理对象:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.*;
public class UserProxy implements InvocationHandler {
private Object obj;
public Object bind(Object obj){
this.obj=obj;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),this);
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
if (method.getName().equalsIgnoreCase("save")) {
System.out.println("before invoke save method");
result = method.invoke(obj, args);
System.out.println("method invoke success!!!");
} else {
result = method.invoke(obj, args);
}
return result;
}
}
测试对象:
public class Tester {
public static void main(String[] args) {
UserProxy userProxy= new UserProxy();
User u =(User)userProxy.bind(new UserImpl());
u.save();
u.test();
}
}
代理接口:
public interface User {
public void save();
public void test();
}
实现类:
public class UserImpl implements User {
public void save(){
System.out.println("Method save invoke!!!");
}
public void test(){
System.out.println("test method!!!1");
}
}
代理对象:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.*;
public class UserProxy implements InvocationHandler {
private Object obj;
public Object bind(Object obj){
this.obj=obj;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),this);
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
if (method.getName().equalsIgnoreCase("save")) {
System.out.println("before invoke save method");
result = method.invoke(obj, args);
System.out.println("method invoke success!!!");
} else {
result = method.invoke(obj, args);
}
return result;
}
}
测试对象:
public class Tester {
public static void main(String[] args) {
UserProxy userProxy= new UserProxy();
User u =(User)userProxy.bind(new UserImpl());
u.save();
u.test();
}
}
本文通过具体示例介绍了 Spring AOP 的实现原理,利用 Java 动态代理技术,在不修改原有代码的情况下添加了切面功能。示例中定义了一个 User 接口及其实现类 UserImpl,并创建了一个代理类 UserProxy 来处理方法调用前后的逻辑。
1913

被折叠的 条评论
为什么被折叠?



