Spring Aop切面@around实现自定义注解
使用@around实现自定义注解计算程序耗时
Spring的思想之一 Aop,面向切面编程,常用的有三个注解@before,@after,@around,我们利用@around来实现一个自定义注解
创建自定义注解 @ExecutionTime
/**
* @Target - 当前注解的作用范围
* ElementType.CONSTRUCTOR - 能够标注在构造方法上
* ElementType.FIELD - 能够标注在属性(全局变量)上
* ElementType.LOCAL_VARIABLE - 能够标注在局部变量上
* ElementType.METHOD - 方法上
* ElementType.PARAMETER - 方法形参
* ElementType.TYPE - 类、接口、内部类
*
* @Retention - 当前注解的有效范围
* RetentionPolicy.SOURCE - 表示当前注解在源码中有效,一旦编译成class文件,注解会丢失
* RetentionPolicy.CLASS - 表示当前注解在源码、class文件中有效,一旦运行时,就会丢失
* RetentionPolicy.RUNTIME - 表示当前注解运行时有效,如果需要配合反射使用,必须是Runtime范围
*
* 方法语法:返回值类型 方法名() [default 默认值];
*/
@Documented
@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExecutionTime {
boolean really() default false;
}
创建切面,来执行操作
@Aspect
@Component
public class AspectByExecution {
Log log = Log.get();//hutool-all
@Around("@annotation(ExecutionTime)")
public Object AspectByExecution(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
ExecutionTime executionTime = method.getAnnotation(ExecutionTime.class);
if (executionTime.really()) {
log.info("计算执行时间的注解已经启用了");
}
Object result = null;
try {
DateTime begin = DateUtil.date();
result = joinPoint.proceed();
DateTime end = DateUtil.date();
log.info("该方法执行时间为:"+DateUtil.between(end,begin, DateUnit.SECOND)+"s");
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return result;
}
}
注解应用
@RestController
public class UserController {
@ExecutionTime(really = true)
@GetMapping("getInfo")
public String getInfo() throws InterruptedException {
CollectionTest collectionTest = new CollectionTest();
collectionTest.result();
String string = "Hello";
return string;
}
}