Annotations in Java – Custom annotations

Hello everyone, it’s been a long time since I saw the last post that someone said let me start the Spring series blog as soon as possible so I don’t have to buy books. Here I feel responsible to say to you, do not have the habit of only reading blog without reading, many people think blog come quickly, learn quickly, grasp the key point. I admit, reading a blog is a quick way to start, of course you choose a good blog, to be honest, the author is ashamed, really only understand a little superficial, a lot of things are picked up by others. Many things are also in the learning stage. And the author has a lot of knowledge is not necessarily all right, only for your reference. In fact, really want to a series of just to learn thoroughly, the author still strongly recommend reading, see some Taobao, JINGdong structure to write the book, although to slow, but very comprehensive, very systematic. If the blog as a meal when the dish, then reading is undoubtedly our staple rice, a bit of health knowledge all know that eating staple rice or pasta is the most tonic for the body. Ok, so much, this article is ready to share custom annotations in Java for a while, because many of my friends around me, it seems that many do not know what annotations are, only know how to use, but do not know the underlying principle of annotations. In this article, I would like to share it with you.

  1. Overview of annotations in Java
  2. Four meta-annotations
  3. Custom annotations

1. Overview of annotations in Java

The first thing to note is that annotations are definitely not provided by Spring. They come with the JDK, and the JDK itself has many built-in annotations, such as @override. The annotation function is to give special meaning to annotated classes, methods, etc. How to generate custom meaning is the annotation processor, which will be discussed in the next article.

2. Four meta-annotations

Meta annotations are, in other words, the JDK’s built-in annotations. In fact, when we custom annotation, annotation to our custom annotation, for example:

@Target(ElementType.TYPE)
public @interface Table {
    public String tableName() default "className";
}
Copy the code

Forget about the syntax, Table is actually a custom annotation that I made, so if I can use @table, then this @target is actually a meta-annotation. The JDK comes with the following meta annotations:

  1. @Target
  2. @Retention
  3. @Documented
  4. @Inherited
@Target

To describe the scope of the annotation, an enumeration ElementType is specified as follows:

  1. CONSTRUCTOR: Used to describe the CONSTRUCTOR
  2. FIELD: Describes the domain
  3. LOCAL_VARIABLE: Used to describe local variables
  4. METHOD: Describes methods
  5. PACKAGE: Used to describe packages
  6. PARAMETER: describes parameters
  7. TYPE: Used to describe a class, interface (including annotation TYPE), or enum declaration

eg:

@Target(ElementType.METHOD)
public @interface Dog {
    
}
Copy the code

As you can see, my Dog annotation only applies to methods.

2. @Retention

The level at which the annotation information needs to be saved is used to describe the annotation life cycle, which is also determined by an enumeration RetentionPoicy, which I will not list, including the annotation how to determine the annotation life cycle, I will not go into details, because based on my years of experience with the annotation, RetentionPoicy.RUNTIME: RetentionPoicy.RUNTIME: RetentionPoicy.RUNTIME: RetentionPoicy.

3. @Documented

If you want to document annotations with Javadoc, wear this. How do you write a document? I never write a document. ^_^)

4. @Inherited

An @Inherited meta-annotation is a markup annotation. @Inherited indicates that an annotated type is Inherited. If an annotation type with the @Inherited annotation is applied to a class, the annotation will be applied to a subclass of that class. Notice that the @Inherited Annotation type is Inherited by a subclass of the annotated class. A class does not inherit annotations from the interface it implements, and a method does not inherit annotations from the method it overloads.

There’s only one annotation that’s useful, and that’s @target, so just pay attention. You can’t just add notes wherever you want.

3. Custom annotations

In addition to the meta annotations above, we will talk about how to customize annotations. By the way, custom annotations are also called composite annotations. Let’s talk about custom annotation formats:

  1. Stick to the format. Don’t mess with it.
  2. Only public or default can be used. For example, a String value (); I’m going to set this method to the default defaul type;
  3. Define the type of the annotation parameter that can only be:
  • All basic data types (int, float, Boolean, byte, double, char, long, short)
  • Type String
  • The Class type
  • Enum type
  • The Annotation type
  • All of the above types of arrays
  1. The method name is the name of the attribute supported by the annotation, like the common value.
  2. Represents the default value of the property name if it is not specified.

Okay, let me give you an example:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Dog {
    public String dog(a) default "";
}
Copy the code

I define a Dog annotation that has an attribute called Dog, which is a String, and the default value is “”. I can use it like this, @dog (Dog =” yellow “), or I can use it like this directly, without specifying the Dog property, default is “”.

Okay, so you can see that this defines an annotation, and you might be wondering, what’s the use of this, even if I add it to a specific class, it doesn’t really work. I’m going to share a little bit of experience with you here. Custom annotations can be used in two ways:

  1. Custom annotation handlers are designed to implement semantics for your custom annotations (such as the @dog annotation method, which prints all the call information to the log system when called). The next blog post will cover custom annotation handlers.
  2. Use with Spring.

Before I get into how Spring works with you, one thing that you might miss is that annotations can be combined, as shown in the figure above. You can add not only Canadian annotations, but other custom annotations. This is fun. Let me give you an example:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Dog {
    public String dog(a) default "";
}
Copy the code

I added @Component to the @dog annotation so that it has @component functionality (added to the Spring container as a bean). Now, in passing, the difference between the property modifier public and the default

  • Attributes modified by public can be overridden, but the default cannot. Here’s an example:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
@Dog
public @interface StupidDog {
    public String dog(a) default"I'm a StupidDog";
}
Copy the code

I’ve now defined a StupidDog annotation that overrides the Dog attribute of @dog and changes the default value from “” to “I’m a StupidDog”..

Okay, back to the topic, see how composite annotations can have the power of annotated annotations. Take the @dog annotation with the @Component annotation. When a class is annotated, for example:

@Dog
public class TestService {... }Copy the code

We know that the TestService will be added to the Spring container as a Bean, but what’s the use of that? This is very useful! This differentiates beans in the Spring container, as shown in the following code snippet:

// CTX is Spring's ApplicationContext
// // gets all Spring beans annotated with Dog
Map<String, Object> serviceBeanMap = ctx.getBeansWithAnnotation(Dog.class); 
Copy the code

As you can see, Spring beans with special markup (custom annotations) can be fetched through the ApplicationContext! Don’t underestimate this feature if you want to do something special to a class of Spring beans after the Spring container has been initialized. Custom annotations can help you tell the difference.

conclusion

For example, Spring @Componenet (@componenet, Spring @componenet, Spring @componenet, Spring @componenet, Spring @componenet, Spring @componenet) As mentioned above, so far yes, in the next article I will share with you the custom annotation processing, which allows you to customize annotations to achieve their own unique functions. It’s Friday. Have a good weekend. Go out and play. Work overtime less, take care of your health, do it, don’t and demand can not pass, can push push. Over,Have a good day .