Java annotations in how it works

What is a comment

Notes can be described in one word, that is, metadata, that is, a description of the data. So, we can say that the source metadata annotation code. For example, the following code:

@Override
public String toString() {
return "This is String Representation of current object.";
}
复制代码

The above code, the rewrite toString () method and used @Override annotations.

In fact, @ Override this method is to tell the compiler (metadata describing the method of) a rewrite method, if the method does not exist in the parent class, the compiler will error, suggesting that the method does not override the parent class method. If you accidentally misspelled, for example, the toString () written toStrring () {double r}, and there is no use @Override notes that the program was still able to compile and run, but the run and the results will be materially different than expectations.

Annotation is applied to a class, method, parameters, variables, and packet constructor declaration special modifiers. It is a choice by the JSR-175 standard describes a tool for metadata. Use annotations help readers.

Why introduce notes

Before using the Annotation (even after use), XML is widely used to describe metadata. I do not know when to start some applications developers and architects found XML maintenance are going bad. They want to use something tightly coupled and code, rather than as XML and code are loosely coupled (and in some cases even completely separate) Code Description. If you search for "XML vs. annotations" in Google, you'll see a lot of debate on this issue. The most interesting is the fact that in order to separate XML configuration code and configuration introduced. Both views may make you very puzzled, the two views seem to constitute a cycle, but each has advantages and disadvantages. Let's understand the difference between the two through an example.

If you want to apply the settings a lot of constants or parameters, in this case, XML is a good choice, because it does not connect with a particular code. If you want a method statement for the service, Annotation would be better to use it, because of the need in this case annotations and methods tightly coupled together, developers must also realize this.

Another very important factor is the Annotation defines a standard way of describing metadata. Prior to this, developers often use custom metadata in their own way. For example, using labeled interfaces, comments, transient keyword, and so on. Each programmer defines the metadata in its own way, unlike Annotation this standard way.

How annotated works

When the time to comment on the label or a method of a class or a member or an input variable parameters, there must be a mechanism corresponding to the annotation on annotation classes, methods, member variables and parameters of certain process.

Annotation is very simple to write, annotate itself can be said to be a class. Annotation definitions can be compared with the definition of the interface. Look at an example, a standard annotation @Override:

package java.lang;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
复制代码

You can see, @ Override annotation seems to do nothing, then it is how to check the function of the same name in the parent class? @Override defined only annotation metadata does not include the business logic, business logic implemented user is annotated.

For @Override notes, its users JVM virtual machine is working in the bytecode level, checks at compile time, its processing mechanism is mainly JVM internal processing.

Another example in Spring @Service annotation, Spring IOC container scanning start time will each class, all annotations are denoted as their sub @Component @Service Bean class for processing.

Write a custom annotation

JDK5.0 version offers four yuan notes in java.lang.annotation, special notes Other notes:

  • @Documented - whether to add annotation information in the document java

  • @Retention - the definition of the life cycle of the annotation

  • @Target - notes for what

  • @Inherited - whether to allow subclass inherits the comment

@Retention annotation defines the annotation of the life cycle, at what stage is discarded,

  • RetentionPolicy.SOURCE - discarded at compile time. These annotations at the end of the compiler will no longer have any meaning, they do not write byte code. @Override, @SuppressWarnings belong to such comments.

  • RetentionPolicy.CLASS - class loading when discarded, is useful in the bytecode file. NOTE Using this way by default.

  • RetentionPolicy.RUNTIME - are never dropped, the run also keep the notes, so you can use reflection to read the annotation information. Custom annotation commonly used in this way.

@Target - indicates that the annotations are used where. If you do not clear that the comment can be placed anywhere. Annotation attributes are compatible.

  • ElementType.TYPE: used to describe the class, interface or enum declaration

  • ElementType.FIELD: instance variables used to describe the

  • ElementType.METHOD

  • ElementType.PARAMETER

  • ElementType.CONSTRUCTOR

  • ElementType.LOCAL_VARIABLE

  • ElementType.ANNOTATION_TYPE another comment

  • ElementType.PACKAGE for recording information package java file

Then, the internal notes in the end is how to define it? Annotations supports only basic types, String and enumerated types. Note that all attributes are defined as a method and allows to provide default values.

Define a @AuthCheck annotation, SpringMVC controller acting on the method.

package com.liuning.sys.auth;

import static java.lang.annotation.ElementType.METHOD;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Target(METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthCheck {
	String value() default "";
}
复制代码

Notes is only one property, you could simply call "value", no longer need to use the property name indicated.

Spring interceptors in HandlerInterceptor business logic @AuthCheck annotation, a reflection mechanism used here.

@Override
public boolean preHandle(HttpServletRequest request, 
                         HttpServletResponse response, 
                         Object handler) throws Exception {
	HandlerMethod hm = (HandlerMethod) handler;
	AuthCheck ac = hm.getMethodAnnotation(AuthCheck.class);
	if (ac != null) {
		if (ac.value() == "Login") {
			//进行业务逻辑操作
		}
	}
	return true;
}
复制代码

The following example demonstrates how to use the above comments. Use the annotation method when the user calls will require the user logged on.

@PostMapping("/list")
@AuthCheck(value = "Login")
public List<User> getUserList(@RequestBody @Valid User user) {
    
    return userService.getUserList(user);
}
复制代码

Guess you like

Origin juejin.im/post/5d1b2312f265da1bc23f913e