标签:count Springboot 自定义 class public 耗时 用于 注解 annotation
使用Springboot 自定义注解完成 统计函数耗时功能
pom 导入依赖
建立springboot项目,在pom中导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
自定义注解 costTime
package com.costtime.annotation.entity;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CostTime {
}
其中
元注解:负责注解其他注解
@Target,@Retention,@Documented,@Inherited
@Target:用于描述注解的使用范围
1.CONSTRUCTOR:用于描述构造器
2.FIELD:用于描述域
3.LOCAL_VARIABLE:用于描述局部变量
4.METHOD:用于描述方法
5.PACKAGE:用于描述包
6.PARAMETER:用于描述参数
7.TYPE:用于描述类、接口(包括注解类型) 或enum声明
@Retention: 定义了该Annotation被保留的时间长短:
1.SOURCE:在源文件中有效(即源文件保留)
2.CLASS:在class文件中有效(即class保留)
3.RUNTIME:在运行时有效(即运行时保留)
@Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。
@Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。
定义一个切面类,用于定义处理请求内容
package com.costtime.annotation.aop;
@Aspect
@Component//使用spring容器进行管理
@Slf4j
public class CostTimeAspect {
/**
* 首先定义一个切点
*/
@org.aspectj.lang.annotation.Pointcut("@annotation(com.counttime.annotation.entity.CostTime)")
public void countTime() {
}
@Around("costTime()")
public Object doAround(ProceedingJoinPoint joinPoint) {
Object obj = null;
try {
long beginTime = System.currentTimeMillis();
obj = joinPoint.proceed();
//获取方法名称
String methodName = joinPoint.getSignature().getName();
//获取类名称
String className = joinPoint.getSignature().getDeclaringTypeName();
log.info("类:[{}],方法:[{}]耗时时间为:[{}]", className, methodName, (System.currentTimeMillis() - beginTime)/1000 + "秒");
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return obj;
}
}
定义Controller,测试结果
package com.counttime.annotation.controller;
@RestController
public class test {
@CostTime
@RequestMapping(value = "/count")
public String countTime(@RequestParm("count") count) {
if(count == 0)
count = 1000;
for (int i = 0; i < count; i++) {
}
return "complete the method!";
}
}
通过游览器访问,并获取控制台打印信息
标签:count,Springboot,自定义,class,public,耗时,用于,注解,annotation 来源: https://blog.csdn.net/Fly_TheWind/article/details/114553987
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。