Taking advantage of the more textual challenges in August, comb some knowledge points of Spring Boot, also do a series of summary.

preface

When you learn the Spring framework, you must understand and implement two powerful features, AOP (aspect oriented) and IOC (Inversion of Control). One of the most common aspects of learning AOP is using aspect logging (just ask every interview that Spring must have AOP, mention AOP must have logging). Next, let’s look at a small Demo of how to add logging using custom annotations.

Spring Boot implements custom annotations

Depend on the introduction of

First, we create a Spring Boot project and add Maven dependencies to spring-boot-starter aop. The Spring-boot-starter – AOP module itself provides dependencies for Spring-AOP, AspectJRT, and AspectJweaver, and contains all the functionality we need to implement custom annotations.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Copy the code

Custom annotations

As a first step, let’s create the @savesystemlog annotation that we need to customize. This is a method level annotation to annotate the methods that we need to monitor. Let’s start by creating our custom annotation class SaveSystemLog

import java.lang.annotation.*;
/** * define a method level@SaveSystemLogComments to indicate methods that need to be monitored: *@author Administrator
 */
@Target(ElementType.METHOD)
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
public @interface SaveSystemLog {
    /**
     * 操作名称
     */
    String value(a) default "";
    /** * Log type */
    String type(a) default "1";
}
Copy the code

Step 2, create the aspect implementation class SystemLogAspect,

public class SystemLogAspect {
    @Pointcut("execution(* com.tyaa.client.controller.*.*(..) ) && @annotation(com.tyaa.client.annotation.SaveSystemLog)")
    public void pointcut(a) {}@Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        Object result = null;
        long beginTime = System.currentTimeMillis();
        try {
            // Execution method
            result = point.proceed();
        } catch (Throwable e) {
            log.error(e.getMessage());
        }
        // Execution duration (milliseconds)
        long time = System.currentTimeMillis() - beginTime;
        // Save logs
        saveLog(point, time);
        return result;
    }

    private void saveLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SaveSystemLog logAnnotation = method.getAnnotation(SaveSystemLog.class);
        System.out.println("Log saved successfully:"+logAnnotation.value()); }}Copy the code

Finally, let’s write a test method, add our custom annotation @savesystemlog to the method, and run it to see the results.

public class Test1 {
    @RequestMapping("/log")
    @savesystemlog (value = "test log ")
    public void saveLog(a){
        System.out.println("123"); }}Copy the code

As you can see, our custom annotation is already in effect, so we can implement the logging aspect functionality by adding it to the method in future development.

Function is introduced

As you can see in the demo above, we added @Target and @Retention annotations to the annotation class when we implemented the custom annotation function. So what do these two notes do? Let’s look at each one. The first is the @target annotation, which is used to place the annotation on a class, method, constructor, variable, etc., whose value is an enumeration. In our demo, we use elementType.method, which describes the METHOD. Then there is the @Retention annotation, which is meant to indicate the lifetime of the annotation, or the Retention position of the annotation. There are three lifecycles in annotations, i.e

  1. Retentionpolicy. SOURCE: Annotations are kept in the SOURCE file only. When the Java file is compiled into a class file, the annotations are discarded;
  2. Retentionpolicy.class: annotations are retained in the CLASS file, but discarded by the JVM when the CLASS file is loaded. This is the default lifecycle;
  3. Retentionpolicy. RUNTIME: Annotations are not only stored in the class file, but also exist after the JVM loads the class file.

conclusion

I believe that through a simple Demo above, you should learn how to create a custom annotation, hope this way can give you development to help. We’ll cover some of the other aspects of Spring Boot in a few more articles, and hopefully you’ll learn something new.