Spring AOP 动态代理


文章主要是《精通Spring 4.x企业应用开发实战》笔记

AOP是Aspect Oriented Programing,“面向方面编程”
Spring AOP底层使用动态代理技术在运行期织入增强代码,生成代理类或者子类,这个类中已经融合了逻辑代码和增强代码,在AOP中我们实际上调用的就是这个类

动态代理分类

使用了两种代理机制:
1.基于JDK的动态代理;
2.基于CGLib的动态代理。

实现一段程序执行时间的监测

1.普通实现

当我们在代码中进行一些监测时,可以这么写代码;先定义一个监测接口ForumService ,接口实现类ForumServiceImpl,监测实现类PerformanceMonitor,监测信息类MethodPerformance

这是监测接口ForumService

package noaop;

/**
 * 被监测类接口
 */
public interface ForumService {
   
    void removeTopic(int topicId);
    void removeForum(int forumId);
}

这是接口实现类ForumServiceImpl,在方法中前后分别调用了PerformanceMonitor监测类的begin和end方法进行监测执行时间

package noaop;

/**
 * 被监测类
 */
public class ForumServiceImpl implements ForumService {
   
    @Override
    public void removeTopic(int topicId) {
   
        PerformanceMonitor.begin("noaop.ForumServiceImpl.removeTopic");//执行前时间
        System.out.println("模拟删除topic记录:" + topicId);
        try {
   
            Thread.currentThread().sleep(20);
        } catch (Exception e) {
   
            throw new RuntimeException(e);
        }
        PerformanceMonitor.end();//执行后时间
    }

    @Override
    public void removeForum(int forumId) {
   
        PerformanceMonitor.begin("noaop.ForumServiceImpl.removeForum");
        System.out.println("模拟删除forum记录:" + forumId);
        try {
   
            Thread.currentThread().sleep(40);
        } catch (Exception e) {
   
            throw new RuntimeException(e);
        }
        PerformanceMonitor.end();
    }
}

这是监测实现类PerformanceMonitor,使用ThreadLocal实现线程安全

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值