AOP的应用场景

1,AOP思想:基于代理的思想,对原来的对象,创建代理对象,在不修改原来对象代码的情况下,通过代理对象,修改功能代码,从而对原来业务代码进行调整。

2,AOP的使用场景:

  I,记录日志。

 II,监控性能。

III,权限控制。

IV,缓存优化。

 V,事务管理。

3,Aop的实现方式:JDK动态代理和CGLIB动态代理

  JDK动态代理针对于有接口实现的类:

  public interface UserDao{

   public void saveUser();

  }

  public class UserDaoImpl implements UserDao{

     @Override

     public void saveUser(){

        System.out.println("hello");

   }
}

JDK动态代理实现:

   final UserDao  = new UserDaoImpl();

   UserDao proxy = (UserDao)proxy.newProxyInstance(userDao.getClass().getClassLoader(),userDao.getClass().getInterfaces,new InvocationHandler(){

        //  InvocationHandler是一个回调接口,回调的时候执行的invoke方法

         @Override

         public Object invoke(Object proxy,Method method,Object[] args)throws Throwable{

             System.out.println("world");

             Object result = method.invoke(userDao,args);

             return result; 

        }

   });

   proxy.saveUser();

}

console:

 hello

 world

CGLIB动态代理主要针对没有接口实现的对象:

public class LinkManDao{

   public void save(){

       System.out.println("hello");

   }

}

CGLIB动态代理实现:

final LinkManDao linkManDao = new LinkManDao();

Enhancer enhancer = new Enhancer();

enhancer.setSuperClass(linkManDao.getClass());

enhancer.setCallBack(new MethodIntercepter(){

   @Override

   public Object intercept(Object proxy,Method method,Object[] args,MethodProxy methodProxy)throws Throwable{

      System.out.println("world");

      Object result = method.invoke(linkManDao,args);

       return result;

  }

});

LinkManDao proxy = (LinkManDao)enhancer.create();

proxy.save();

 

  • 6
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值