Spring AOP学习笔记(一)
AOP使用代理机制
AOP可以在不修改源码的情况下对代码进行增强
AOP使用动态代理有阆中实现方式当我们实现了接口的时候Spring会使用JDK动态代理 没有实现接口就会自动切换到 Cglib(类似于Javassit)动态代理 cglib 是生成子类对象来实现的动态代理
JDK动态代理:《查》
动态代理的实现
public class MyJDKProxy implements InvocationHandler {
private UserDao userDao;
public MyJDKProxy(UserDao userDao) {
this.userDao = userDao;
}
// 编写工具方法:生成代理:
public UserDao createProxy(){
UserDao userDaoProxy = (UserDao)
Proxy.newProxyInstance(userDao.getClass().getClassLoader(),
userDao.getClass().getInterfaces(), this);
return userDaoProxy;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
if("save".equals(method.getName())){
System.out.println("权限校验================");
}
return method.invoke(userDao, args);
}
}
Cglib 动态代理增强一个类中的方法:
public class MyCglibProxy implements MethodInterceptor{
private CustomerDao customerDao;
public MyCglibProxy(CustomerDao customerDao){
this.customerDao = customerDao;
}
// 生成代理的方法:
public CustomerDao createProxy(){
// 创建 Cglib 的核心类:
Enhancer enhancer = new Enhancer();
// 设置父类:
enhancer.setSuperclass(CustomerDao.class);
// 设置回调:
enhancer.setCallback(this);
// 生成代理:
CustomerDao customerDaoProxy = (CustomerDao) enhancer.create();
return customerDaoProxy;
}
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy
methodProxy) throws Throwable {
if("delete".equals(method.getName())){
Object obj = methodProxy.invokeSuper(proxy, args);
System.out.println("日志记录================");
return obj;
}
return methodProxy.invokeSuper(proxy, args);
}
}
还没有评论,来说两句吧...