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;
    }
}

结果展示

自定义注解执行结果

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值