使用注解装配Aop学习笔记

  1. 编写注解类
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface MetricTime {
       String value();
    }
    
  2. 编写Aspect类
    @Aspect
    @Component
    // 不需要获取注解类(注意@annotation参数为注解类全名称)
    public class MetricAspect {
        @Around("@annotation(com.yicj.study.mq.aspect.MetricTime)")
        public Object metric(ProceedingJoinPoint joinPointm)throws Throwable{
            //String name = metricTime.value();
            long start = System.currentTimeMillis();
            try {
                return joinPointm.proceed() ;
            } finally {
                long end = System.currentTimeMillis();
                // 写入日志或发送至JMX:
                System.out.println("===> [Metrics] : " + (end -start) +"s");
            }
        } 
    }
    @Aspect
    @Component
    // 获取注解实例(注意@annotation参数方法中的MetricTime2的参数名称)
    public class MetricAspect2 {
       @Around("@annotation(metricTime)")
       public Object metric2(ProceedingJoinPoint joinPointm, MetricTime metricTime)throws Throwable{
           String name = metricTime.value();
           long start = System.currentTimeMillis();
           try {
               return joinPointm.proceed() ;
           } finally {
               long end = System.currentTimeMillis();
               // 写入日志或发送至JMX:
               System.out.println("===> [Metrics] " + name + " : " + (end -start) +"s");
           }
       }
    }
    
  3. 编写业务类并使用@MetricTime注解
    @Service
    public class UserService {
        @MetricTime("register")
        public String register(String name, String password, String email){
            try {
                Thread.sleep(345);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "success" ;
        }   
    }
    
  4. 参考:https://www.liaoxuefeng.com/wiki/1252599548343744/1310052317134882
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值