Annotation-->spring Configuration

Source: Internet
Author: User
Tags throw exception

It is necessary to learn a little more about JDK 5.0 's new annotation (Annotation) technology because spring supports @aspectj, and @aspectj itself is a JDK 5.0-based annotation technology. So learning the annotated knowledge of JDK 5.0 helps us to better understand and Master spring's AOP technology.

Understanding Annotations

For Java developers, when writing code, in addition to the source program, we use the Javadoc tag to annotate classes, methods, or member variables so that the Javadoc tool can be used to generate Javadoc documents that match the source code. These javadoc tags, such as @param, @return, and so on, are annotation tags that provide annotated information for third-party tools that describe program code. Friends who have used Xdoclet will be more impressed, like struts, hibernate provide xdoclet tags, and use them to quickly generate the corresponding program code configuration file.

JDK5.0 annotations can be seen as the extension and development of Javadoc tags and xdoclet tags. In JDK5.0, we can customize these tags and get the annotations in the class in the reflection mechanism of the Java language to accomplish certain functions.
Annotations are collateral information for the code, which follows a basic principle: annotations do not directly interfere with the operation of the program code, and the code works correctly regardless of adding or removing annotations. The Java language interpreter ignores these annotations, and the third-party tool is responsible for processing the annotations. Third-party tools can use annotations in the code to indirectly control the operation of program code, which reads the annotated information through the Java reflection mechanism and changes the logic of the target program based on that information, which is the approach that spring AOP takes to provide support for @aspectj.

The design of many things must follow the most basic principle, in order to prevent the robot harm mankind, sci-fi writer Asimov in 1940 proposed the "Three Principles of Robotics": first, the robot can not harm human beings; Second, the robot shall obey the orders of mankind, except for the first one; Robots should be able to protect themselves, with the exception of the first one that violates the order. This is an ethical program given to robots, which has been used by robotics academia as a guideline for robot development.



a simple annotation class

In general, third-party tools are not only responsible for handling specific annotations, they also provide definitions of these annotations, so we usually just need to focus on how to use annotations. But defining the annotation class itself is not difficult, and Java provides the syntax for defining annotations. Next, we'll start by writing a simple annotation class, as shown in Listing 7-1:

Code Listing 7-1 Needtest annotation class

Java code
  1. Package Com.baobaotao.aspectj.anno;
  2. Import Java.lang.annotation.ElementType;
  3. Import java.lang.annotation.Retention;
  4. Import Java.lang.annotation.RetentionPolicy;
  5. Import Java.lang.annotation.Target;
  6. @Retention (retentionpolicy.runtime) //① Statement of retention period for annotations
  7. @Target (Elementtype.method)//② declares that the target type of the annotation can be used
  8. Public @interface needtest {//③ definition annotations
  9. boolean value () default true; ④ declaring annotation members
  10. }



The new Java syntax specifies that the annotation class is defined using the @interface modifier, as shown in ③, where a callout can have more than one member, and a member declaration and an interface method declaration are similar, where we define only one member, as shown in ④. The declaration of a member has the following limitations:

    • Members are declared in a non-argument-no-throw exception, such as Boolean value (String str), Boolean value (), throws exception, and so on, which are illegal;
    • You can specify a default value for a member by default, such as String level (), default "Low_level", and "int High" () default 2 is legal, and of course you can not specify a default value;
    • Member types are restricted, and valid types include primitive types and their enclosing classes, String, class, enums, annotation types, and array types of the above types. such as Forumservice value (), List foo () is illegal.



In ① and ②, the annotations we see are Java predefined annotations, called meta Annotations (meta-annotation), that are used by the Java compiler to affect the behavior of the annotation class. @Retention (Retentionpolicy. Runtime) indicates that needtest this annotation can be read by the JVM at run time, the retention term type of the annotations is defined in the Java.lang.annotation.Retention class, as described below:

    • Source: The annotation information remains only in the source file of the target class code, but the corresponding bytecode file is no longer retained;
    • class: The annotation information goes into the bytecode file of the target class code, but the ClassLoader does not load the annotations into the JVM when it loads the bytecode file , that is, the runtime cannot get the annotation information;
    • Runtime: The annotation information is retained after the target class is loaded into the JVM, and the annotation information in the class can be read at run time through the reflection mechanism.
    •    Target (Elementtype.method) indicates that the annotation can only be applied to the method of the target class, Needtest. The application target for annotations is defined in the Java.lang.annotation.ElementType class:
    • Type: Class, interface, annotation class, enum declaration, and corresponding annotations are called type annotations;
    • FIELD: class member variable or constant declaration, The corresponding annotation is called the field value annotation;
    • method: The corresponding annotation is referred to as the method annotation, and
    • PARAMETER: At the parameter declaration, the corresponding annotation is called the parameter annotation;
    • CONSTRUCTOR: At the constructor declaration, the corresponding annotation is called the constructor annotation;
    • local_variable: local variable declaration, the corresponding annotation is called the regional variable annotation;
    • Annotation_ Type: The annotation class declaration, the corresponding annotation is called the annotation class annotation, ElementType. The TYPE includes elementtype.annotation_type;
    • Package: At the packet Declaration, the corresponding note is called the package annotation.



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 @needtest (true). When an annotation class has more than one member, an assignment number is not used if only the value member is assigned, and if more than one member is assigned, you must use an assignment number, such as declareparents (value = "Naivewaiter", Defaultimpl = Smartseller.class). Note Classes can have no members, and annotations with no members are called identity annotations, and the interpreter processes the annotations to identify whether they exist or not; In addition, all annotation classes implicitly inherit from Java.lang.annotation.Annotation, but annotations do not allow explicit inheritance to other interfaces.

We want to annotate the methods of the business class with the needtest annotation so that the test tool can activate or deactivate the test of the business class based on the annotation situation. Once you have written the Needtest annotation class, you can use it in other classes.

using Annotations

We use needtest annotations in Forumservice to annotate whether business methods need testing, as shown in Listing 7-2:

Code Listing 7-2 Forumservice: Using annotations

Java code
  1. Package Com.baobaotao.aspectj.anno;
  2. Public class Forumservice {
  3. @NeedTest (value=true) ①
  4. public void Deleteforum (int forumid) {
  5. System.out.println ("Delete Forum module:" +forumid);
  6. }
  7. @NeedTest (value=false) ②
  8. public void deletetopic (int postid) {
  9. System.out.println ("Delete Forum theme:" +postid);
  10. }
  11. }



If the annotation class and the target class are not in the same package, you need to refer to the annotation class through import. At ① and ②, we use Needtest to annotate the Deleteforum () and the Deletetopic () methods respectively. When annotating annotations, annotation members can be assigned in the following format:

Reference @< annotation Name > (< member name 1>=< member value 1>,< member name 1>=< member value 1>,...)



If the member is an array type, it can be assigned through {} , such as the members of the Boolean array can be set to {true,false,true}. Here are some examples of annotation annotations:

Example 1, multi-member annotations:

Java code
    1. @AnnoExample (id= 2868724, synopsis = "Enable time-travel",
    2. Engineer = "Mr. Peabody", date = "4/1/2007")



Example 2, a member of the annotation, the member name is value. You can omit the member name and the assignment symbol:

Java code
    1. @Copyright ("bookegou.com All Right Reserved")



Example 3, annotations with no members:

Java code
    1. @Override



Example 4, the member is an annotation of a string array:

Java code
    1. @SuppressWarnings (value={"Unchecked","Fallthrough"})



Example 5, the member is an annotation of the annotation array type:

Java code
    1. @Reviews ({ @Review (grade= Review.grade.excellent,reviewer= "DF"),        
    2.             @Review (Grade=review.grade.unsatisfactory,reviewer=
    3.                       comment= "this method needs an  @Override  annotation")})   



@Reviews annotations have a member of the @review annotation array type, @Review the annotation type has three members, where reviewer, comment are string types, but comment has a default value, and grade is a member of the enumeration type.

Since the retention period for needtest annotations is retentionpolicy.runtime type, the annotation information for forumservice methods can still be accessed through the reflection mechanism when Forumservice is loaded into the JVM.

Access Annotations

As mentioned earlier, annotations do not directly affect the operation of the program, but third-party programs or tools can use the annotations in the code to complete special tasks, indirect control program operation. For annotations of the Retentionpolicy.runtime retention period, we can access the annotations in the class through the reflection mechanism.

In JDK5.0, reflective objects such as package, Class, Constructor, method, and field have new ways to access annotation information: <t extends Annotation>t getannotation ( Class<t> Annotationclass), which supports direct return of annotation objects via generics.

Below, we access the annotations through reflection to derive the test requirements that are hosted by the @needtest annotations in the Forumservice class, as shown in Listing 7-3:

Code Listing 7-3 Testtool: accessing annotations in code

Java code
  1. Package Com.baobaotao.aspectj.anno;
  2. Import Java.lang.reflect.Method;
  3. Public class Testtool {
  4. public static void Main (string[] args) {
  5. //① get Forumservice corresponding class object
  6. Class clazz = Forumservice.   class;
  7. //② get Forumserivce corresponding to the method array
  8. Method[] methods = Clazz.getdeclaredmethods ();
  9. System.out.println (methods.length);
  10. For (Method method:methods) {
  11. //③ Gets the annotation object that is marked on the method
  12. Needtest NT = method.getannotation (needtest.  class);
  13. if (nt! = null) {
  14. if (Nt.value ()) {
  15. System.out.println (Method.getname () + "() need to test");
  16. } Else {
  17. System.out.println (Method.getname () + "() No test required");
  18. }
  19. }
  20. }
  21. }
  22. }



At ③, through the reflection object of the method, we get the Needtest annotation object annotated on the method, then we can access the member of the annotation object, and get the test demand of the Forumservice class method. Run the above code to output the following information:

Reference Deleteforum () requires testing
Deletetopic () No test required

Annotation-->spring Configuration

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.