AOP实现方式
原理:在ioc中创建了一个原对象的代理对象,而这个对象是AOP增强过的。
动态代理
JDK
1.1 实现接口
interface UserService{
void add();
void del();
}
1.2 原对象
class UserServiceImpl implements UserService {
@Override
public void add() {System.out.println("add");}
@Override
public void del() {System.out.println("del");}
}
1.3 创建 InvocationHandler 处理器
class MyInvocationHandler implements InvocationHandler {
private Object target;
public MyInvocationHandler(Object target){
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before method");
// 执行原对象方法
Object res = method.invoke(target, args);
System.out.println("after method");
return res;
}
}
1.4 使用
public static void main(String[] args) throws InterruptedException {
// 创建并使用代理对象
UserServiceImpl userService = new UserServiceImpl();
MyInvocationHandler myInvocationHandler = new MyInvocationHandler(userService);
UserService proxy = (UserService) Proxy.newProxyInstance(
userService.getClass().getClassLoader(),
userService.getClass().getInterfaces(),
myInvocationHandler
);
proxy.add();
proxy.del();
}
------------------------------------------------------
before method
add
after method
before method
del
after method
Process finished with exit code 0
CGLib
原理:CGLib直接操作字节码,生成类的子类,重写类的方法完成代理。