Java annotation mechanism-implementation principle of Spring Automatic Assembly

Source: Internet
Author: User

JDK has added support for the annotation mechanism. In fact, I used JDK 1.6 when I was learning java. Besides @ override and @ suppresswarnings (the latter is generated by ide ......) I have never touched any other products.

During the interview before entering the company, the technicians asked me questions about annotations. I said I could generate a CHM manual ...... Now, I think it's really plain. I have made the comments and annotations exactly the same.

  

Annotations are mainly used when Spring framework is needed, especially springmvc. This is because we will find its strength: preprocessing.

Annotation is actually equivalent to a tag, which allows you to dynamically operate on members with the tag at runtime (we will not discuss the source code, documentation, and class files.

Three conditions are required for annotation implementation (we are discussing advanced applications similar to Spring Automatic Assembly): annotation declaration, annotation elements, and code for using annotation elements.

  

The first is the annotation declaration, and the annotation is also a type. We also need to write code to define it, as shown below:

1 package annotation; 2 3 Import Java. lang. annotation. elementtype; 4 Import Java. lang. annotation. retention; 5 import Java. lang. annotation. retentionpolicy; 6 Import Java. lang. annotation. target; 7 8/** 9 * Custom annotation, used to configure method 10*11 * @ author johness12 * 13 */14 @ retention (retentionpolicy. runtime) // indicates that the annotation still exists at runtime 15 @ target (elementtype. method) // indicates that the annotation can be used on the Method 16 public @ interface sayhiannotation {17 string paramvalue () Default "johness "; // indicates that my annotation requires a parameter named "paramvalue". The default value is "johness" 18}

 

Then we use the annotation elements:

1 package element; 2 3 Import annotation. sayhiannotation; 4 5/** 6 * class where the elements to use sayhiannotation are located 7 * because we have defined that only methods can use our annotations, we will use multiple methods to test 8*9 * @ author johness10 * 11 */12 public class sayhiemlement {13 14 // common method 15 public void sayhidefault (string name) {16 system. out. println ("hi," + name); 17} 18 19 // use the annotation and pass in the Parameter Method 20 @ sayhiannotation (paramvalue = "Jack ") 21 public void sayhiannotation (string name) {22 system. out. println ("hi," + name); 23} 24 25 // use annotation and the default parameter 26 @ sayhiannotation27 public void sayhiannotationdefault (string name) {28 system. out. println ("hi," + name); 29} 30}

Finally, it is our operation method (it is worth mentioning that although there are certain specifications, you do not have to waste energy, you only need to ensure that your operation code is executed when you want it ):

1 package main; 2 3 Import Java. lang. reflect. invocationtargetexception; 4 Import Java. lang. reflect. method; 5 6 Import element. sayhiemlement; 7 Import annotation. sayhiannotation; 8 9 public class annotionoperator {10 public static void main (string [] ARGs) throws exceptions, exceptions, invocationtargetexception, classnotfoundexception {11 sayhiemlement element = new sayhiem LEMENT (); // Initialize an instance for calling method 12 method [] Methods = sayhiemlement. class. getdeclaredmethods (); // obtain all methods 13 14 for (method: Methods) {15 sayhiannotation annotationtmp = NULL; 16 if (annotationtmp = method. getannotation (sayhiannotation. class ))! = NULL) // check whether our annotation 17 method is used. invoke (element, annotationtmp. paramvalue (); // if our annotation is used, we use the "paramvalue" parameter value in the annotation as a method parameter to call Method 18 else19 method. invoke (element, "Rose"); // if our annotation is not used, we need to call the method in a normal way 20} 21} 22}

Result: Hi, Jack
Hi, johness
Hi, Rose

As you can see, annotations are a good method for preprocessing (the preprocessing here is different from the compilation principle )!

 

Next, let's take a look at how spring uses the annotation mechanism to complete automatic assembly:

  

The first is to let spring automatically assemble the operations for us. There are two types: Inherit Org. springframework. web. context. support. springbeanautowiringsupport class or add annotations such as @ component/@ controller and declare the context: component-scan element in the spring configuration file (only required by the annotation method.

Let's talk about how the inheritance method implements automatic assembly. Let's open the spring source code to view the springbeanautowiringsupport class. We will find the following statement:

1 public SpringBeanAutowiringSupport() {2         processInjectionBasedOnCurrentContext(this);3     }

 

As we all know, the default parent class no-argument constructor will be called during Java instance construction. Spring uses this to execute the "Code of operation elements! (I was shocked at first sight! It's a wonderful idea. Sure enough, experts should be good at using Java)

I will not talk about it much later, but I still need to correct some people's points: setter is also required to use annotation-based automatic assembly to complete injection. This is obviously wrong! Let's take a look at the call sequence of spring annotation assembly (Inheritance Method) Methods: org. springframework. Web. Context. Support. springbeanautowiringsupport # springbeanautowiringsupport =>

Org. springframework. Web. Context. Support. springbeanautowiringsupport # processinjectionbasedoncurrentcontext =>

Org. springframework. Beans. Factory. annotation. autowiredannotationbeanpostprocessor # processinjection =>

Org. springframework. Beans. Factory. annotation. injectionmetadata # injection (inheritance, method rewriting ). Finally, let's look at the method body of the injection method:

 1 /** 2          * Either this or {@link #getResourceToInject} needs to be overridden. 3          */ 4         protected void inject(Object target, String requestingBeanName, PropertyValues pvs) throws Throwable { 5             if (this.isField) { 6                 Field field = (Field) this.member; 7                 ReflectionUtils.makeAccessible(field); 8                 field.set(target, getResourceToInject(target, requestingBeanName)); 9             }10             else {11                 if (checkPropertySkipping(pvs)) {12                     return;13                 }14                 try {15                     Method method = (Method) this.member;16                     ReflectionUtils.makeAccessible(method);17                     method.invoke(target, getResourceToInject(target, requestingBeanName));18                 }19                 catch (InvocationTargetException ex) {20                     throw ex.getTargetException();21                 }22             }23         }

Although incomplete, it can be basically determined that this automatic assembly uses the Java radiation mechanism.

 

You are welcome to move to our chat group and pass the time together when you are bored:

Or contact me via QQ:

(Last editing time: 09:52:27)

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.