编程知识 cdmana.com

Your development tool spring custom annotation

Preface

   Custom annotation is a powerful tool in development , It's often used . It was mentioned in the last article that Custom verification comments Usage of . Recently, however, we have received such a demand , It is mainly used to encrypt the returned data of some interfaces . So it's natural to think of Custom annotation +AOP To achieve such a function . But for custom annotations , Just stay on the surface of the use , Do not do Know what it is , And know why . So this article is to understand the user-defined annotation, which is a powerful tool for development .

What is a custom annotation ?

The official definition of

  An annotation is a form of metadata, that can be added to Java source code. Classes, methods, variables, parameters and packages may be annotated. Annotations have no direct effect on the operation of the code they annotate.

Google Translate

   Annotations are a form of metadata , Can be added to Java In the source code . class , Method , Variable , Parameters and packages can be annotated . Annotations have no direct effect on the operation of the code they annotate .

After reading this definition, I can't feel it , Don't panic, practice and know .

Create a custom annotation

   Let's review the scenario of requirements first , It's aimed at xx The data returned by the interface needs to be encrypted . I talked about using Custom annotation +AOP To achieve this function . So let's first define an annotation called Encryption, By Encryption Annotations modify the interface , The returned data should be encrypted .

public @interface Encryption {
}

   You'll find that creating custom annotations , It's as simple as building a normal interface . It's just that the keywords used are different . On the underlying implementation , All defined annotations are automatically inherited java.lang.annotation.Annotation Interface .

Write the corresponding interface

@Encryption
@GetMapping("/encrypt")
public ResultVo encrypt(){
    return ResultVoUtil.success(" Different technology house ");
}

@GetMapping("/normal")
public ResultVo normal(){
    return ResultVoUtil.success(" Different technology house ");
}

Write facets

@Around("@annotation(com.hxh.unified.param.check.annotation.Encryption)")
public ResultVo encryptPoint(ProceedingJoinPoint joinPoint) throws Throwable {
  ResultVo resultVo = (ResultVo) joinPoint.proceed();

  //  Get comments 
  MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
  Method method = methodSignature.getMethod();
  Encryption annotation = method.getAnnotation(Encryption.class);

  //  If it's marked , Then encrypt 
  if(annotation != null){
    //  To encrypt 
    String encrypt = EncryptUtil.encryptByAes(JSON.toJSONString(resultVo.getData()));
    resultVo.setData(encrypt);
  }

  return resultVo;
}

test result

   This is the time , You will find that the returned data is not encrypted . So why is this ? As the saying goes, don't panic when you encounter problems , First take out your cell phone and send a circle of friends ( It's a little off topic ). The reason for this is , Lack of @Retention Yes @Encryption Modification of , Let's add it to .

@Retention(RetentionPolicy.RUNTIME)
public @interface Encryption {

}

Continue testing

   At this time, the returned data is encrypted , Note that the custom annotation is in effect .

Test the common interface

   of no avail @Encryption The interface of , The returned data is not encrypted . At this point, the requirement has been realized , Now it's time to understand the principle .

@Retention

@Retention What is the role

  Retention It's translated as " Retain " It means . It means that its function is , Used to define the lifecycle of an annotation , And you need to specify RetentionPolicy,RetentionPolicy There are three strategies , Namely :

  • SOURCE - Annotations are only kept in the source file , When Java File compiled into class When you file , The note is abandoned .
  • CLASS - The annotation is reserved until class file , but jvm load class The document was abandoned , This is the default lifecycle .
  • RUNTIME - Annotations are not only saved to class In file ,jvm load class After the document , There is still .

Choose the right life cycle

   The first thing to do is to define the life cycle RUNTIME > CLASS > SOURCE . Generally, if you need to get annotation information dynamically at runtime , Only use RUNTIME. If you want to do some preprocessing at compile time , For example, generate some auxiliary code with CLASS. If you just do some checking operations , such as @Override and @SuppressWarnings, You can choose SOURCE.

Almost all of the custom annotations in our actual development are used RUNTIME

   In the beginning @Encryption Not used @Retention Define its life cycle . So lead to AOP It is always empty at the time of acquisition , If it is empty, the data will not be encrypted .

   It's too crude . Then give him something more , Add a @Target.

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Encryption {

}

@Target

  @Target Annotations define where custom annotations can be used . This is the same as parameter verification , Set the rules , Prevent misuse and cause problems . According to the above requirements, it can only be used in the method . Depending on the scene , It can also be used in more places . For example, attributes 、 package 、 On the constructor and so on .

  • TYPE - class , Interface ( Including annotation types ) Or enumerate
  • FIELD - Field ( Include enumeration constants )
  • METHOD - Method
  • PARAMETER - Parameters
  • CONSTRUCTOR - Constructors
  • LOCAL_VARIABLE - local variable
  • ANNOTATION_TYPE - Annotation type
  • PACKAGE - package
  • TYPE_PARAMETER - Type parameter
  • TYPE_USE - Type of use

   The above two are more commonly used meta annotations ,Java A total of 4 A meta note . You may ask what meta annotations are ? The role of meta annotation is to annotate other annotations .

@Documented

  @Documented Is used to annotate custom annotations , If you use @Documented Marking the , It's generating javadoc When you do, you will put @Documented The annotations are shown . It doesn't work , Just get to know .

@Inherited

   By @Inherited Embellished notes , When used on a parent class, its subclass also has the annotation . Simply put , When used in the parent class by @Inherited Embellished notes @InheritedTest when , Subclasses that inherit it also have @InheritedTest annotation .

This can be explained separately

Annotation element type

   Refer to our experience in defining interfaces , Methods and constants can be defined in an interface . But in custom annotations , Only one thing can be defined : Annotation type elements Annotation type element.

In fact, it can be simply understood that only methods can be defined , But it's different from the method in the interface .

Note the following points when defining annotation type elements :

  • The access modifier must be public, Do not write default is public.
  • The type of the element can only be the basic data type 、String、Class、 Enumeration type 、 Annotation type .
  • type() Method parameters cannot be defined in parentheses , Just a special grammar . But it can go through default Keyword settings " The default value is ".
  • If there is no default value , The type element must be assigned a value when using annotation .

Continue to reform

   Demand is always changing . The interface that needs to be encrypted is only used AES To encrypt , Later, it is told that some interfaces need to be used DES encryption . In this case , We can put it in the notes , Add a configuration item , To choose which way to encrypt .

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Encryption {

    /**
     *  Encryption type 
     */
    String value() default "AES";
  
}

Interface adjustment

@Encryption
@GetMapping("/encrypt")
public ResultVo encrypt(){
    return ResultVoUtil.success(" Different technology house ");
}

@Encryption(value = "DES")
@GetMapping("/encryptDes")
public ResultVo encryptDes(){
    return ResultVoUtil.success(" Different technology house ");
}

@GetMapping("/normal")
public ResultVo normal(){
    return ResultVoUtil.success(" Different technology house ");
}

adjustment AOP

@Around("@annotation(com.hxh.unified.param.check.annotation.Encryption)")
public ResultVo encryptPoint(ProceedingJoinPoint joinPoint) throws Throwable {
  ResultVo resultVo = (ResultVo) joinPoint.proceed();

  //  Get comments 
  MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
  Method method = methodSignature.getMethod();
  Encryption annotation = method.getAnnotation(Encryption.class);

  //  If it's marked , Then encrypt 
  if(annotation != null){
    //  To encrypt 
    String encrypt = null;
    switch (annotation.value()){
      case "AES":
        encrypt = EncryptUtil.encryptByAes(JSON.toJSONString(resultVo.getData()));
        break;
      case "DES":
        encrypt = EncryptUtil.encryptByDes(JSON.toJSONString(resultVo.getData()));
        break;
      default:
        break;
    }
    resultVo.setData(encrypt);
  }

  return resultVo;
}

   So far the transformation is finished . You can find annotation element types , In use , Operating element types are like manipulating attributes . When parsing , The operation element type is like in the operation method ..

Tips

  • When the element type has no annotation , It can be written as @Encryption and @Encryption() equivalent .
  • When an annotation has only one annotation type element , And the name is value. When use @Encryption("DES") and @Encryption(value = "DES") equivalent .

Points of attention

  • The lifecycle of annotations needs to be specified according to the actual situation @Retention.
  • Use @Target To limit the use of annotations , To prevent annotations from being misused .
  • If annotations are configured on methods , So we have to go from Method Get... On object . If it's configured on properties , It needs to correspond to the Field Object up to get . Anyway, where to use it , Just go and get it .

summary

   Annotation can be understood as a sign . You can put these marks on the key nodes in the program code , It doesn't change the execution logic of the original code . The program can then detect these markers at compile or run time , In making the corresponding operation . Combined with the little scene above , You can get the basic process of using custom annotations :

  1. Definition notes --> Create a business based on .
  2. Using annotations --> Use it in the corresponding code .
  3. Parsing annotations --> Flag detected at compile time or runtime , And carry out special operations .

Previous review

ending

   If it helps you , You can comment more , A little bit better , You can also go to my homepage , Maybe there are articles you like , You can also pay attention to it , thank you .

   I'm a different tech house , Make a little progress every day , Experience a different life . See you next time !

版权声明
本文为[Different technology house]所创,转载请带上原文链接,感谢

Scroll to Top