Comments on Java annotations

Source: Internet
Author: User

Annotation definition (from Baidu Encyclopedia): instructs the compiler how to treat your custom Annotation, the compiler will leave the Annotation information in the class file, but not be read by the virtual machine, but only for the compiler or tool to provide information when the program runs.

With the popularity of 0 configuration, the use of annotations is becoming more and more popular, and annotation learning is also necessary. Recently learned a few notes of spring, here to share with you the understanding of the annotations.
First of all, we look at the source code of @controller this annotation:

?
12345678910 package org.springframework.stereotype;// 省略import以及一些注释@Target({ElementType.TYPE})  @Retention(RetentionPolicy.RUNTIME)  @Documented  @Component  public @interface Controller {      String value() default "";  }


It is not difficult to see that the key word of the note is @interface, much like an interface, is not able to instantiate, however, we in the actual use, usually through the reflection mechanism, to get an instance of the annotation interface, the logical processing, the following sample to see this use. (The annotation method named value has a more specific usage, which is mentioned later.) )

Its main body, defines a value () method, in fact, it is not only a method definition, but also a property definition of the annotation. When we use annotations for labeling, this is the case: @Controller (value= "Mycontroller"), and in the analytic Judgment, the Controller.value () method is used to obtain this specific value " Mycontroller ". Then look at the default, which is followed by value (), which means that the defaults are a value and there is actually an effect that indicates that the Value property can not be entered. Therefore, when we use the controller, we can use it directly @controller, do not need to give value, if we remove the default, do not specify value, the compilation will fail.

Take a look at the annotations in front of this annotation definition. @Target, as the name implies, specifies the purpose of the current annotation use. If you use development tools such as Eclipse, place your mouse over the Elementtype.type, and you'll see its comments, roughly meaning that this annotation is placed in a class, interface, or enumeration type declaration. In other words, our @controller annotations can only be placed in front of classes, interfaces, enumeration definitions, not in member properties, methods, parameters, and so on. You can follow ElementType, which defines the "Type,field,method,parameter,constructor,local_variable,annotation_type,package" enumeration, It is not difficult to guess according to the comments (or from enumerating the English meanings.) This, on the other hand, explains that proper naming helps to improve code readability, and it is easy to know that annotations can be implemented in various places of the class file.

@Retention (retentionpolicy.runtime), Retention may not be good to guess, but see the back of the runtime, the spirit of a shock, speculation should be related to the "runtime." Review the API help documentation, Retention "indicates how long comments for comment types should be retained." This reservation will be used in conjunction with Retentionpolicy (retention's strategy). The controller's retention policy is run-time, so that the annotation can be obtained by reflection when the code is running. The benefits of this strategy, specific implementation cases can be referenced by the Spring bean Scan and AOP interception annotation implementation (Spring configuration file Component-scan base-package configuration, the Spring Bean Factory will scan each class under the package, Generate related beans based on their annotations. We can analyze @component, @Service, @Autowired, etc., and its strategy is runtime).

@Documented, if you need to document through the Javadoc tool, you will be judged by this annotation, thus preserving the comments (specifically, no practice, no blind flattery).

@Component this annotation on the controller, can be seen as "Controller also has the role of component." In fact, the current spring scan beans only look for component annotations. We will see that there are @component annotations on @Service, @Repository. Said here again have to digress under the topic, to compare the @service, @Controller, @Repository, @Component the difference between the notes. Theoretically, the @Service is on a bean that is annotated to provide service, @Controller is on the C of the annotated MVC, @Repository is used by the storage-layer bean, and @component is the bean that the annotation does not differentiate between service or control. In fact, these kinds of annotations end up in spring in bean form in the Bean factory, and there's no difference. As a result, spring scans beans with @component as a token, @Service, @Controller, @Repository can be seen as a function reservation: In the future, when the classes of these three annotations are bean-initialized, To do extra enhancement processing.

After splitting the annotations, we find that the annotations are less mysterious. The next step is to design a note for yourself:
Custom annotations:

?
1234567 @Target(ElementType.TYPE)  @Retention(RetentionPolicy.RUNTIME)  public @interface MyAnnotation {  String name() default "";// 名字  Class<!--?--> procClass() default Object.class;// 处理类的类型  String value() default "";// 比较特别  }


Annotations Use classes:

?
123 // 标注时,name、procClass和value当做属性直接设值@MyAnnotation(name="Lily",procClass=TestAnnotation.class,value="abc")publicclassSomeClass{}


Test:

?
123456789 //get annotations through reflection someclass some = new someclass (); //get an instance of Myannotation myannotation annotationclass = Some.getclass (). Getannotation (myannotation. class //judgment Logic, name and Procclass as methods to call string annotationname = Annotationclass.name (); system.out.println (annotationname); class<!--?--> Clazz = Annotationclass.procclass (); system.out.println (clazz);


The value defined above () when used, if you do not set other properties, only set value, you can do this: @MyAnnotation ("abc"), at this point, values are "ABC", the other default values. (String type is not restricted.) Of course, other methods of myannotation need to provide default values. )

The above is a simple example, you can modify the target, add or subtract methods to achieve their own needs of the annotations.

Finally, everyone is welcome to shoot bricks.

Comments on Java annotations

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.