The learning of JAVA annotations and the understanding of spring annotations

Source: Internet
Author: User
Tags ming reflection

When you start using frames like spring and hibernate,mybatis the year before, you go to annotations. Until some time ago, suddenly began to curiosity about the annotations. Why do you write annotations? You don't need a lot of configuration files. So I looked at some of the data and had a preliminary understanding of the annotations.

Introduction: What is annotation.

In the IDE, we can link the @requestmapping annotation in spring MVC and discover the following source

@Target (value = {elementtype.method, elementtype.type})
@Retention (value = retentionpolicy.runtime)
@ Documented
@Mapping public
@interface requestmapping {public

    string[] Value () default {};

    Public requestmethod[] Method () default {};

    Public string[] params () default {};

    Public string[] Headers () default {};

    Public string[] consumes () default {};

    Public string[] produces () default {};
}
This is actually the wording of the annotation. From here we can find that the annotation is written relatively simple, as long as the intface before the @, you can define an annotation. But there are a few other annotations that we don't quite understand, and how spring works through this annotation.

First: What is the role of annotations.

1 generate documents, such as @param, @return, @author, etc. in our IDE.

2 Compile-time format check. The most common is @override, @SuppressWarnings and so on.

3 tracking code dependencies to implement alternate profile functionality. The above source example is actually this role.

Second: meta-annotation

Include all the original annotations and interfaces that are required to define custom annotations in the package java.lang.annotation. such as interface Java.lang.annotation.Annotation is an interface inherited by all annotations, and is automatic inheritance and is not specified when defined, similar to all classes automatically inheriting object. Looking at Documented.class, you can see that this is an excuse. It has three annotations (@Documented, @Retention, @Target), in addition to @inherited, which constitute 4 meta annotations.

@Documented include this annotation in Javadoc, which represents that this annotation is extracted from the Javadoc tool as a document.

The contents of a Doc document will vary depending on the content of the information for this annotation. Quite with @see, @param and so on.

@Retention indicates at what level the annotation information is saved. The optional parameter values are in the enumeration type Retentionpolicy, including:
Retentionpolicy.source annotations will be discarded by the compiler
Retentionpolicy.class annotations are available in the CLASS file but are discarded by the VM
The Retentionpolicy.runtime VM will also retain annotations at runtime, so you can read the annotation information through the reflection mechanism.

The @Target indicates where the annotation is used, and the possible values are in the enumeration class Elemenettype, including:
Elemenettype.constructor Builder Declaration
Elemenettype.field Domain declaration (including enum instance)
Elemenettype.local_variable local variable declaration
Elemenettype.annotation_type action on the annotation volume statement
Elemenettype.method Method declaration
Elemenettype.package Package Statement
Elemenettype.parameter parameter declaration
Elemenettype.type class, interface (including annotation type) or enum declaration

@Inherited allow subclasses to inherit annotations from the parent class.

then: Let's write our own notes.

/** * Custom annotation * @author Fly/@Documented @Target ({elementtype.method, elementtype.type}) @Retention (R

    etentionpolicy.runtime) Public @interface annotationtest {public String name () default "";
Public String sex () default "male"; }
/**  * Annotation Test  *  * @author Fly  */@AnnotationTest (sex = "male", name = "Zhang Fei") public class Myannotationtes  t {    @AnnotationTest (sex = "male", name = "Fly")     public void Setfly () {   }     @AnnotationTest (sex = "female", name = "Li Ming")     public void setliming () {   }     PU Blic static void Main (string[] args) {       /Check class myannotationtest contains @annotationtest annotations   &NBSP ;     if (MyAnnotationTest.class.isAnnotationPresent (Annotationtest.class)) {           //If present get annotations             annotationtest annotation = (annotationtest) Myannotati
OnTest.class.getAnnotation (Annotationtest.class);
            System.out.println (annotation);            //Get annotation Properties             SYSTEM.OUT.PRINTLN (annotation
. sex ());      
      SYSTEM.OUT.PRINTLN (Annotation.name ());
            SYSTEM.OUT.PRINTLN ("///////////////////////////////////////////");
            method[] _methods = MyAnnotationTest.class.getDeclaredMethods ();             (method: _methods) {            &NBSP ;
  System.out.println (method);                 if (method.isannotationpresent (Annotationtest.class)) {  &NB Sp 
                annotationtest test = method.getannotation (Annotationtest.class);                     SYSTEM.OUT.PRINTLN ("annotationtest method=" + metho


D.getname () + ", name=" + test.name () + ", sex=" + test.sex () + ")");                             }       &nbsp }    }}
The test results are as follows:

@test. Annotationtest (sex= male, name= Zhang Fei)
Man
Zhang Fei
///////////////////////////////////////////
public static void Test. Myannotationtest.main (java.lang.string[])
public void Test. Myannotationtest.setliming ()
Annotationtest (Method=setliming,name= Li Ming, sex=)
public void Test. Myannotationtest.setfly ()
Annotationtest (method=setfly,name=fly,sex= male)

Here, we have a basic understanding of the annotation, the use of annotations and reflective type is inseparable. We can use the annotations in the code to indirectly control the operation of program code, which reads the annotation information through the Java reflection mechanism and changes the logic of the target program based on that information. But how do we use annotations? How to make annotations work, such as spring and other frameworks, how to apply annotations.

Then: The depth of the annotation understanding
We continue to illustrate this issue in conjunction with spring's control inversion and dependency injection.

Look at the following code, first of all, a Iuser interface that contains a login method. Then another Chinese login method and the English login method have implemented the Iuser interface.

Public interface Iuser {public

    void login ();
}
public class Chineseuserimpl implements Iuser {
    @Override public
    void Login () {
        System.err.println ("User logon.") ");
    }
}
public class Englishuserimpl implements Iuser {
    @Override public
    void Login () {
        System.err.println ("User Login. ");
    }
}
And then there's a test class that's going to inject the Iuser interface

@AnnotationTest public
class Test {

    private iuser Userdao;

    Public Iuser Getuserdao () {return
        Userdao;
    }

    @AnnotationTest (Nation = "Chineseuserimpl") public
    void Setuserdao (Iuser userdao) {
        This.userdao = userdao;< c18/>} public

    void Logintest () {
        userdao.login ();
    }
}
What we achieve is the setter injection method. To tie in with this example, I have also made a slight revision of @annotationtest.

@Documented
@Target ({elementtype.method, Elementtype.type, Elementtype.field})
@Retention ( retentionpolicy.runtime) Public
@interface annotationtest {public
    
    String Nation () Default "";
}
And then introduce a class container, like the role of spring container

public class Container {public static test Getbean () {Test test = new test (); if (Test.class.isAnnotationPresent (Annotationtest.class)) {method[] methods = Test.class.getDeclaredMethods ()
            ;
                For [method Method:methods] {System.out.println (method); if (Method.isannotationpresent (Annotationtest.class)) {Annotationtest annotest = method.getannotation
                    (Annotationtest.class);  System.out.println ("Annotationtest" (field=) + method.getname () + ", nation=" + annotest.nation ()
                    + ")");
                    Iuser Userdao;
                        try {Userdao = (iuser) class.forname ("test." + annotest.nation ()). Newinstance ();
                    Test.setuserdao (Userdao);
                    The catch (Exception ex) {Logger.getlogger (Container.class.getName ()). log (Level.severe, NULL, ex); }
                }} else {System.out.println ("no annotation mark.)
        ");
    return test; }
}
Inside the container I use reflection to get the annotation attribute nation, and then the interface in the test class is implemented concretely. The container here is called an external container that can parse our annotations or XML configuration files to reduce coupling.

Finally we will test the code as follows

/**
 * Annotation Test * *
 @author Fly
/public class Myannotationtest {public

    static void Main (string[) args) {
        test test = Container.getbean ();
        Test.logintest ();
    }
The test results are as follows:

public void Test. Test.logintest () public
void Test. Test.setuserdao (test. Iuser)
annotationtest (field=setuserdao,nation=chineseuserdaoimpl) public
test. Iuser test. Test.getuserdao ()
user logged in.
If I put the test class
@AnnotationTest (Nation = "Chineseuserimpl")

Modified into

@AnnotationTest (Nation = "Englishuserimpl")
Structure becomes

public void Test. Test.logintest () public
test. Iuser test. Test.getuserdao () public
void Test. Test.setuserdao (test. Iuser)
annotationtest (Field=setuserdao,nation=englishuserimpl)
User Login.

Summary

1. All annotation classes are implicitly inherited from Java.lang.annotation.Annotation, and annotations do not allow explicit inheritance to other interfaces.

2, the annotation can not directly interfere with the operation of the program code, regardless of adding or deleting annotations, the code can run normally. The Java language interpreter ignores these annotations and is responsible for processing the annotations by a third-party tool.

3, a note can have more than one member, a member declaration and an interface method declaration are similar, here we only define a member, the declaration of a member has the following limitations:
A   member declares in a way that no parameter throws an exception, such as Boolean value (String STR), Boolean value () throws exception, and so on,
B   can specify a default value for members through default, such as String level () default "Low_level", int high () default 2 is legal, and of course you can not specify a default value;
C)   member types are restricted, and legitimate types include the original type and its encapsulated class, String, class, enums, annotation type, and array type of the above type. such as Forumservice value (), List foo () is illegal.
D)   If the annotation has only one member, the member name must be named value (), and the member name and assignment number (=) can be ignored when used, such as @description ("instance using annotations"). When the annotation class has more than one member, the assignment number is also not used if the value member is assigned, and if multiple members are assigned at the same time, the assignment number must be used, such as @declareparents (value = "Naivewaiter", Defaultimpl = Smartseller.class).
e)   Annotation classes can have no members, annotations without members are called identity annotations, and interpreters are processed to identify the existence of annotations;

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.