Want to write your own framework? Not if you can’t write java annotations


Want to write your own framework? Not if you can't write java annotations

Use notes for a while, always use them for a long time

After Java back-end development entered the spring family bucket era, developing a micro service to provide a simple addition, deletion, modification and query interface is very simple. The operation is as fierce as a tiger. Looking back at the code, a pile of annotations were added: @ controller @ Autowired @ value. Annotation oriented programming has become an indispensable operation for everyone.

Imagine that Java programmers can cry without annotations

Since annotation is so important and easy to use, do you know the implementation principle of annotation? I guess you can only use annotations, not write your own annotations (manual funny).

Well, the following content takes you to write an annotation from scratch and uncover the mystery of annotation.

The original annotation is not mysterious

In vernacular, an annotation is a tag or a special annotation. If there is no operation to parse these tags, it is nothing.

The format of annotation has its own special syntax like the same kind or method. This syntax will be described in detail below.

How to parse annotations? This requires the powerful reflection function of Java. Reflection should be used by everyone. You can get all kinds of information about this class through class objects, such as member variables, methods, etc. can annotation tags be obtained through reflection? Of course.

Therefore, the principle of annotation is actually very simple. In essence, it dynamically obtains annotation marks through the reflection function, and then performs different operations according to different annotations. For example, @ Autowired can inject an object to assign values to variables.

Is it very restless to see here? Come on, let’s make an annotation.

Make a rocket. Write an annotation yourself

For your understanding, let’s first introduce a scenario: online education is popular. The manager asked me to write a module to realize the student information management function. Considering the distributed concurrency problem, the manager asked me to add the distributed lock.

The manager asked me how many days can I finish it? I said at least three days. If yes, the following code is added:

Want to write your own framework? Not if you can't write java annotations

Before annotation

After the manager left, I was thinking, can I just write in one day and spend the remaining two days writing blogs and rowing? Suddenly, the inspiration came. I can draw out the repeated code logic and implement it with annotations. Ha ha, write it quickly.

After using the annotation, the whole method is much refreshing. My little sister HR praised me for writing well.

Want to write your own framework? Not if you can't write java annotations

After using annotation

The code has been written and put into the library. Now I’m rowing and blogging. Is it very simple, elegant and awesome? How to do it? It is mainly divided into three steps:   1 open the refrigerator door, 2 put the elephant in, 3 close the refrigerator door  。 All right, let’s move on.

The first step is to define an annotation

Want to write your own framework? Not if you can't write java annotations

Three components of annotation

An annotation can be simply broken down into three parts:

Part I: annotation body

The definition of annotation is a bit similar to interface, except that the previous one is marked with an @ symbol, which must not be saved.

Part II: annotation variables

The syntax of annotated variables is somewhat similar to the methods defined in the interface. The variable name is followed by a pair of parentheses. The difference is that there can be default values after annotated variables. In addition, the return value can only be java basic type, string type or enumeration class, not object type.

Part III: meta annotation

Meta annotation, to put it bluntly, is the annotation that adds annotation to the annotation. Is it a little dizzy? This annotation is built in advance by JDK and can be used directly. It doesn’t matter if you don’t understand it. Anyway, the number is not large. There are only four in total. Let’s recite it: @ target @ retention @ documented @ inherited

  • Target annotation

Used to describe the scope of use of annotations, that is, where modified annotations can be used.

Annotations can be used to modify packages, types (classes, interfaces, enumerations, annotation classes), class members (methods, construction methods, member variables, values), method parameters and local variables (such as loop variables and catch parameters). When defining annotation classes, @ target can be used to more clearly know which objects it can be used to modify, The specific value range is defined in the elementtype.java enumeration class.

For example, the redis lock annotation we wrote above can only be used for methods.

  • Retention annotation

It is used to describe the time range of annotation retention, that is, the annotation life cycle. Three cycles are defined in the retentionpolicy enumeration class:

public enum RetentionPolicy {

Source, // source file retention
Class, // reserved during compilation, default value
Runtime // reserved during runtime. Annotation information can be obtained through reflection


As we know, @ override annotation can only be kept in the source file, and the annotation disappears after the code is compiled. For example, the redis lock annotation we wrote above is kept until the runtime, and information can be obtained through reflection during runtime.

  • Documented annotation

It is used to describe whether to keep the annotation information when generating help documents for classes using Javadoc tools. It is very simple and will not be explained.

  • Inherited annotation

The annotation modified by the inherited annotation is inherited. If the parent class uses the annotation modified by @ inherited, its subclass will automatically inherit the annotation.

OK, we have defined the annotation in this step, but how does the annotation work? Keep looking.

The second step is to realize the business logic of annotation

In the first step, we found that the defined annotation (@ enablereredislock) has no business logic and only some variables. Don’t forget that our annotation is to enable the redis distributed lock function. How does this annotation realize the function of locking and releasing locks? This requires us to use the powerful function of reflection.

Want to write your own framework? Not if you can't write java annotations

Operation of annotation

Here, with the help of the aspect function, the enablereredislock annotation is used as a pointcut. As long as the annotation is marked on the method, the code logic here will be executed automatically.

After you get the annotation object through the reflection mechanism, you can execute the common logic of locking and unlocking. Redis implements distributed locks. I’m sure you’re familiar with it. I won’t be wordy here.

The third step is to make full use of annotations in the business code

@EnableRedisLock(lockKey = “student”, expireTime = 10, timeUnit = TimeUnit.SECONDS, retryTimes = 5)
public void method1(Student student) {

//Write business logic here


It’s OK to directly add comments on the methods that need to be locked. How about it? Is it very simple? Hurry to use it in your project.

Well, I’ll introduce the content of an annotation by myself. Have you learned it?

  • END –

After reading three things ❤️

If you think this article is very helpful to you, I’d like to invite you to help me with three small things:

  1. Praise, forwarding, and your “praise and comments” are the driving force for my creation.
  2. Pay attention to the official account of “Java didi” and share original knowledge without any time.
  3. Meanwhile, the official account will reply to “666” to get 1000 Internet interview questions free.