Java annotations are a set of metadata that provides data to interpret program code, but annotations are not part of the interpreted code itself. Annotations have no direct effect on how the code works.

The interpretation of annotations on the Internet is too serious and rigid, which is not my style. Although this explanation sounds very technical.

To ease the strangeness of annotations, let me do something interesting. In fact, my first impression of the word “annotations” is not Java annotations, but Zhu Xi’s famous “Annotations to The Four Books”. Why did I have such a big imagination? Because when I try to translate the word Annotation, I get “Annotation” instead of “Annotation.” Zhu Xi’s Commentaries on the Four Books, namely the Great Learning, the Doctrine of the Mean, the Analects of Confucius and Mencius. Want to know, this book but after Ming and Qing dynasty imperial examination question bank and standard answer!

Annotations are a concept introduced in Java SE 5.0 and are a type, along with classes and interfaces. Many developers think annotations have a low status, but they don’t. Annotations like @Transactional, @Service, @RestController, @RequestMapping, @Crossorigin, and so on are becoming more and more common.

01. Why use annotations?

Why use annotations? Let’s start with another question.

The word “cross-domain” sticks to every front-end developer like a dog’s skin plaster; I’m no exception, although I’m not a pure front-end developer.

Cross-domain problems arise because browsers’ same-origin policy, which restricts scripts loaded from one source to access resources from another, effectively isolates potential malicious files and is an important security mechanism.

There are also many solutions to cross-domain problems, such as:

1) the json

2) Nginx proxy

3) “Cross-origin Resource Sharing” (CORS for short) can be said to be the standard practice to deal with cross-domain problems.

I remember that when I first encountered a cross-domain problem, I asked one of my classmates for a solution, and he gave me the following answer.

The first step is to add a filter to web.xml.

<filter>
  <filter-name>contextfilter</filter-name>
  <filter-class>com.cmower.filter.WebContextFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>contextfilter</filter-name>
  <url-pattern>/ *</url-pattern>
</filter-mapping>
Copy the code

Step 2, implement the WebContextFilter class.

public class WebContextFilter implements Filter {
 
    @Override
    public void destroy(a) {}@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse  httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-Control-Allow-Origin"."*");
        httpServletResponse.setHeader("Access-Control-Allow-Headers"."accept,content-type"); 
        httpServletResponse.setHeader("Access-Control-Allow-Methods"."OPTIONS,GET,POST,DELETE,PUT"); 
        chain.doFilter(request, httpServletResponse);
         
    }
 
    @Override
    public void init(FilterConfig arg0) throws ServletException {}}Copy the code

I was devastated to see such a solution. Isn’t it a cross-domain problem that requires so much code?

I am very unhappy with this solution. So I made up my mind to do some research, and after half a day, I finally figured out the “cross-domain” problem and its standard solution, CORS. And found a very compact solution, @Crossorigin, which can easily solve the cross-domain problem by adding this annotation to the Controller class.

Here’s the code.

@RestController
@RequestMapping("course")
@CrossOrigin
public class CourseController {}Copy the code

If THE annotation @crossorigin is not found, I really have to follow the solution provided by my classmates to solve the cross-domain problem. But that would be like selling the family car and driving a carriage when we get around.

That’s why I want to tell you why annotations are used: they make our code look cleaner and more progressive.

02. How do you define annotations?

Annotations need to be defined by the @interface keyword, which is very similar to an interface except that it is preceded by an @. We can open the source of @Crossorigin and take a look.

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CrossOrigin {
	/**
	 * List of allowed origins, e.g. {@code "http://domain1.com"}.
	 * <p>These values are placed in the {@code Access-Control-Allow-Origin}
	 * header of both the pre-flight response and the actual response.
	 * {@code "*"} means that all origins are allowed.
	 * <p>If undefined, all origins are allowed.
	 * @see #value
	 */
	@AliasFor("value")
	String[] origins() default {};
	/**
	 * List of request headers that can be used during the actual request.
	 * <p>This property controls the value of the pre-flight response's
	 * {@code Access-Control-Allow-Headers} header.
	 * {@code "*"}  means that all headers requested by the client are allowed.
	 * <p>If undefined, all requested headers are allowed.
	 */
	String[] allowedHeaders() default {};
	/**
	 * List of supported HTTP request methods, e.g.
	 * {@code "{RequestMethod.GET, RequestMethod.POST}"}.
	 * <p>Methods specified here override those specified via {@code RequestMapping}.
	 * <p>If undefined, methods defined by {@link RequestMapping} annotation
	 * are used.
	 */
	RequestMethod[] methods() default {};
}
Copy the code

As you can see from the code above, annotations are really annotations, and there really is nothing more than a lot of comments and a lot of meta-annotations.

“Meta-annotations”? What is a “meta-annotation”?

A meta-note is a note (noun) used to note (verb) a note (noun). Please feel the richness and depth of Chinese. @Target, @Retention, and @Documented are known as meta-annotations.

1) @ Target

Target means Target, and @target specifies the context in which the annotation is used. What are the scene values?

  • ElementType.ANNOTATION_TYPE: Annotations can be annotated
  • ElementType.CONSTRUCTORThe constructor can be annotated
  • ElementType.FIELD: Fields can be annotated
  • ElementType.LOCAL_VARIABLE: local variables can be annotated
  • ElementType.METHOD: methods can be annotated
  • ElementType.PACKAGE: Packages can be annotated
  • ElementType.PARAMETER: you can annotate parameters within a method
  • ElementType.TYPEYou can annotate types, such as classes, interfaces, and enumerations

2) @ Retention

The word Retention means Retention period. That is, when @Retention is applied to a annotation, it explains how long the annotation will last. Let’s look at the range of values.

  • RetentionPolicy.SOURCEAnnotations are only retained at the source stage and are discarded and ignored when the compiler compiles.
  • RetentionPolicy.CLASSAnnotations are only reserved until compilation and are not loaded into the JVM.
  • RetentionPolicy.RUNTIMEAnnotations can be kept until the application is run and loaded into the JVM, so they can be retrieved while the application is running.

3) @ Documented

Documented is a little bit easier to understand, and it has to do with documentation. The effect is to be able to include elements from annotations into Javadoc.

Once we understand the concept of meta-annotations, isn’t it clearer to look back at the @Crossorigin source code?

If you read the comments in the source code carefully, you’ll see the keywords that appear in the WebContextFilter class, Such as access-Control-allow-origin, access-Control-allow-headers, and access-Control-allow-methods. That is, when we annotate the Controller class with @Crossorigin, SpringMVC can automatically apply a filter to the class at runtime to resolve cross-domain problems.

03. Can annotations be reflected?

Annotations can be obtained by reflection.

1) The Class object’s isAnnotationPresent() method determines whether a specified annotation is applied to the Class.

2) Get the annotation object using the getAnnotation() method.

3) Once you get the annotation object, you can get the value of the property defined when using the annotation.

The following is an example:

@CrossOrigin(origins = "http://qingmiaokeji.com", allowedHeaders = "accept,content-type", methods = { RequestMethod.GET, RequestMethod.POST })
public class TestController {
	public static void main(String[] args) {
		Class c = TestController.class;

		if(c.isAnnotationPresent(CrossOrigin.class)) { CrossOrigin crossOrigin = (CrossOrigin) c.getAnnotation(CrossOrigin.class);  System.out.println(Arrays.asList(crossOrigin.allowedHeaders())); System.out.println(Arrays.asList(crossOrigin.methods())); System.out.println(Arrays.asList(crossOrigin.origins())); }}}// Output: [accept,content-type]
// [GET, POST]
// [http://qingmiaokeji.com]
Copy the code

04. Where are annotations often used?

Transactional: Spring’s support for Transactional management

2) @service: Spring automatically registers this class with the Spring container when it does a package scan.

3) @restController: is a combined annotation of @responseBody and @Controller.

In other words, the code below is the same as the code below.

@RestController
public class HelloController {

    @RequestMapping(value="hello")
    public String sayHello(a){
        return "hello"; }}Copy the code
@Controller
@ResponseBody
public class HelloController {

    @RequestMapping(value="hello")
    public String sayHello(a){
        return "hello"; }}Copy the code

4) RequestMapping: one of the most commonly used annotations in Spring Web applications to map HTTP requests to MVC and REST controller processing.

5) @select: Query statement annotation provided by MyBatis. The following is an example:

@Select("select * from city")
List<City> getCitys(a);
Copy the code

6) There are many, many more, I will not list them all.

The last

I would like to say that annotations are useful for many purposes, mainly:

  • Provide information to the compiler: The compiler can use annotations to detect errors and warnings.
  • Compile-time processing: Software tools can use annotation information to generate code, HTML documents.
  • Runtime processing: Some annotations can accept code extraction while the program is running.

Don’t forget to:


PS: This article was originally published in the wechat public number “Silent King ii”, reply keyword “0” to get the second brother carefully prepared for you the rare edition ebook gift package.