Use Spring Aop to monitor the execution time of each Controller or method

1. Create custom annotations

package com.lishicloud.qc.common.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface TimeOperation {
    //自定义的一个参数,可以在注解后面指定参数,如@TimeOperation(name = "test")
    String name() default "sam";
    String type();
}

2. Create a slice

package com.lishicloud.qc.plugin.aop;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;


@Aspect
@Component
public class TimeAspect {

    //开始时间
    private Long begin;
    //结束时间
    private Long end;

    /**
     * 此注解规定了切入点
     * "@annotation(com.lishicloud.qc.common.annotation.TimeOperation)" 表示标有@TimeOperation注解的方法
     * "execution(public * com.lishicloud.qc.web.*.*(..))" 表示com.lishicloud.qc.web下的所有类中的所有方法
     */
    @Pointcut("@annotation(com.lishicloud.qc.common.annotation.TimeOperation)")
    public void logOperation(){}

    @Before(value = "logOperation()")
    public void before(){
        begin = System.currentTimeMillis();
    }

    @After(value = "logOperation()")
    public void after(){
        end = System.currentTimeMillis();
        System.out.println("用时"+(end - begin)+"毫秒");
    }

}

Note: Java custom annotations

Java started to introduce annotations in 1.5, and currently popular frameworks are using annotations. It is conceivable that annotations are powerful.

The following is an in-depth understanding of java annotations through custom annotations.

1. Create custom annotations

package com.sam.annotation;
import java.lang.annotation.*;

/**
 * @author sam
 * @since 2017/7/13
 */
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyMessage {

    String name() default "sam";

    int num() default 0;

    String desc();

}

@Target, @Retention, @Inherited, @Documented are meta-annotations, which are responsible for annotating other annotations.

  1. Target: Indicates the scope of use supported by the annotation. For the value, please refer to the enumeration ElementType, as follows:
    • ElementType.TYPE //class, interface, enumeration
    • ElementType.FIELD //property
    • ElementType.METHOD //Method
    • ElementType.PARAMETER //parameter
    • ElementType.CONSTRUCTOR //Constructor
    • ElementType.LOCAL_VARIABLE //local variable
    • ElementType.ANNOTATION_TYPE //注解
    • ElementType.PACKAGE //包
  2. Retention: Indicates the length of time the annotation is retained. For the value, refer to the enumeration RetentionPolicy, as follows:
    • SOURCE //Retained in the source file
    • CLASS //class is reserved when compiling
    • RUNTIME // reserved at runtime
  3. Inherited: Indicates that the annotation type is automatically inherited. If an annotation is modified with @Inherited, subclasses of the class to which the annotation acts will also use the annotation.
  4. Documented: Indicates that the element with this annotation can be documented by tools such as javadoc.

2. Create a test class and use custom annotations

package com.sam.annotation;
/**
 * @author sam
 * @since 2017/7/13
 */
public class AnnotationTest {

    @MyMessage(num = 10, desc = "参数a")
    private static int a;


    @MyMessage(name = "Sam test", desc = "测试方法test")
    public void test() {
        System.out.println("test");
    }

}

The properties and methods in this class use custom annotations and specify parameters.

So now you need to parse the custom annotation.

3. Analyzing annotations

Handling custom annotations using reflection

package com.sam.annotation;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 使用反射处理注解
 *
 * @author sam
 * @since 2017/7/13
 */
public class MyMessageProcessor {

    public static void main(String[] args) {

        try {

            //加载annotationTest.class类
            Class clazz = MyMessageProcessor.class.getClassLoader().loadClass("com.sam.annotation.AnnotationTest");

            //获取属性
            Field[] fields = clazz.getDeclaredFields();
            //遍历属性
            for (Field field : fields) {
                MyMessage myMessage = field.getAnnotation(MyMessage.class);
                System.out.println("name:" + myMessage.name() + "  num:" + myMessage.num() + "  desc:" + myMessage.desc());
            }

            //获取类中的方法
            Method[] methods = clazz.getMethods();
            //遍历方法
            for (Method method : methods) {

                //判断方法是否带有MyMessage注解
                if (method.isAnnotationPresent(MyMessage.class)) {
                    // 获取所有注解 method.getDeclaredAnnotations();
                    // 获取MyMessage注解
                    MyMessage myMessage = method.getAnnotation(MyMessage.class);
                    System.out.println("name:" + myMessage.name() + "  num:" + myMessage.num() + "  desc:" + myMessage.desc());
                }
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

}

Running MyMessageProcessor gets the result:

name:sam  num:10  desc:参数a
name:Sam test  num:0  desc:测试方法test

Process finished with exit code 0

The content implemented by the specific custom annotation can be modified in MyMessageProcessor.java.

Since then, I have had a simple understanding of Java's custom annotations.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325905539&siteId=291194637