记录方法运行时间——基于spring的面向切面编程简单实例
2017-02-07 20:40
423 查看
工程中有很多方法需要记录方法的运行时间,本质上这是独立于主业务逻辑且复用性很强的功能,类似的还有权限控制,用户验证,打log等。如果每个方法里都要反复去写是一件很low的事情,但是如果改用切面编程来实现就十分清爽了。
spring中用@Aspect可以定义一个切面类,用@Pointcut定义一个切点表达式方法。Pointcut的execution即是用正则表达式定义的包+类+方法组成的切面场景。针对切面场景,有@Before@After@AfterReturning@AfterThrowing@Around等不同的通知去取方法执行不同阶段的各种上下文。
@Component
@Aspect
public class MethodRunTimeInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(MethodRunTimeInterceptor.class);
private long startTime = 0;
@Pointcut("execution(public * *.*.*())")
public void recordTime() {
}
@Before("recordTime()")
public void before(JoinPoint jp) {
startTime = System.currentTimeMillis();
}
@AfterReturning("recordTime()")
public void afterReturning(JoinPoint jp) {
long spendTime = System.currentTimeMillis() - startTime;
String className = jp.getTarget().getClass().getSimpleName();
String methodName = jp.getSignature().getName();
LOGGER.info("{} {} costs {}ms ",className,methodName,spendTime);
}
}
spring中用@Aspect可以定义一个切面类,用@Pointcut定义一个切点表达式方法。Pointcut的execution即是用正则表达式定义的包+类+方法组成的切面场景。针对切面场景,有@Before@After@AfterReturning@AfterThrowing@Around等不同的通知去取方法执行不同阶段的各种上下文。
@Component
@Aspect
public class MethodRunTimeInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(MethodRunTimeInterceptor.class);
private long startTime = 0;
@Pointcut("execution(public * *.*.*())")
public void recordTime() {
}
@Before("recordTime()")
public void before(JoinPoint jp) {
startTime = System.currentTimeMillis();
}
@AfterReturning("recordTime()")
public void afterReturning(JoinPoint jp) {
long spendTime = System.currentTimeMillis() - startTime;
String className = jp.getTarget().getClass().getSimpleName();
String methodName = jp.getSignature().getName();
LOGGER.info("{} {} costs {}ms ",className,methodName,spendTime);
}
}
相关文章推荐
- 从头认识Spring-3.2 简单的AOP日志实现-需要记录方法的运行时间
- 从头认识Spring-3.6 简单的AOP日志实现(注解版)-需要记录方法的运行时间
- 从头认识Spring-3.2 简单的AOP日志实现-需要记录方法的运行时间
- spring Aop 面向切面编程简单实例
- Golang记录、计算函数执行耗时、运行时间的一个简单方法
- 最简单的记录程序运行时间的方法:[记录PHP程序运行消耗时间]
- AspectJ spring aop 记录某些类中方法执行时间实例
- AspectJ spring aop 记录某些类中方法执行时间实例
- 基于spring3.0.5 mvc 简单用户管理实例
- 记录程序运行时间的程序实例
- Spring:使用JdbcTemplate的简单实例-基于XML文件配置
- 基于spring3.0.5 mvc 简单用户管理实例
- 最简单的动态代理实例(spring基于接口代理的AOP原理)
- spring实例化bean之简单工厂静态方法实例化
- Spring:使用JdbcTemplate的简单实例-基于注释
- Spring面向切面的简单示例(基于XML文件配置)
- Linux下计算程序运行时间的一个简单方法
- Linux下计算程序运行时间的一个简单方法
- 基于OSGi的Virgo Server最简单Spring web实例
- spring3.0框架检测方法运行时间测试(转)