day2.1.5.Spring AOPJDK动态代理实现日志功能

Spring aop介绍

  • AOP(Aspect Oriented Programming)是面向切面编程
    就是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
    简单说 就是在不改变方法原代码的基础上,对方法进行功能增强
    本质上是生成了一个新的类,叫做代理类

  • AOP对程序的扩展方式采用动态代理的方式. (JDK动态代理Cglib动态代理两种方式)
    在这里插入图片描述

Spring jdk动态代理:

JDK的动态代理

  • Proxy类的方法
    Proxy类的静态方法可以创建代理对象
    static Object newProxyInstance(ClassLoader loader, Class[] interfaces, InvocationHandler h)
  • 三个参数
    参数1:ClassLoader loader 类加载器 , 用来加载代理对象
    参数2:Class<?>[] interfaces 目标类的字节码对象数组. 因为代理的是接口,需要知道接口中所有的方法
    参数3:InvocationHandler h 执行句柄, 代理对象处理的核心逻辑就在该接口中

jdk代理实现日志案例:

实现思路:

在这里插入图片描述

实现步骤:

LogSystemTest

public class LogSystemTest {
    public void test01(){
        Person p = new Person("jack","123456");
        //生成代理类,创建该类对象
        PersonDaoImpl personDao = new PersonDaoImpl();
        Logger logger = LoggerFactory.getLogger(PersonDaoImpl.class);
        ClassLoader classLoader=PersonDaoImpl.class.getClassLoader();//与原来类一样
        Class<?>[] interfaces=PersonDaoImpl.class.getInterfaces();//与原来类一样
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                调用Dao类的update(person)
//                调用Logger类的debug(“update  parameter return”)
                //update delete add 的执行
                //开始
                long start = System.currentTimeMillis();
                Object returnVal = method.invoke(personDao,args);
                long time = System.currentTimeMillis()-start;
                logger.debug("方法名:"+method.getName()+" 参数"+ Arrays.toString(args)+" 返回值:"+returnVal+" 耗时"+time);
                return returnVal;
            }
        };
        IPersonDao personDao2= (IPersonDao) Proxy.newProxyInstance(classLoader,interfaces,handler);
        //       personDao.add(p);
        personDao2.update(p);
//        pers
        onDao.delete(1);
    }
}

IPersonDao

public interface IPersonDao {
     void add(Person p);
     void update(Person p);
     void delete(int id);
}

PersonDaoImpl

public class PersonDaoImpl implements IPersonDao{

    public void add(Person p){
        System.out.println("执行 数据库的insert");
    }
    public void update(Person p){
        System.out.println("执行 数据库的update");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void delete(int id){
        System.out.println("执行 数据库的delete");
    }
}

运行结果

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值