您当前的位置: 首页 >  spring

杨林伟

暂无认证

  • 3浏览

    0关注

    3337博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

09Spring - AOP底层实现

杨林伟 发布时间:2019-04-02 17:55:45 ,浏览量:3

AOP的底层实现

Spring的AOP的底层用到了两种代理机制:

JDK动态代理: 针对实现了接口的类产生代理

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 mCustomerDao;

    public MyCgLibProxy(CustomerDao customerDao) {
        mCustomerDao = 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);
    }
}

关注
打赏
1662376985
查看更多评论
立即登录/注册

微信扫码登录

0.0580s