Spring Boot Annotations Simple Summary (Continuous Supplementation)

The biggest feature of Spring Boot is that it does not require an XML configuration file, can automatically scan the package path to load and inject objects, and can be automatically configured according to the jar package under the classpath.

Spring

@SpringBootApplication

This is the most core annotation of Spring Boot, used on the Spring Boot main class, to identify this is a Spring Boot application, used to enable the capabilities of Spring Boot.

In fact, this annotation is a combination of the three annotations @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan, which can also be used to replace the @SpringBootApplication annotation.

1.

Allows Spring Boot to automatically configure annotations. After enabling this annotation, Spring Boot can configure Spring Beans according to the package or class under the current classpath.

2.

This is an annotation added by Spring 3.0 to replace the applicationContext.xml configuration file. All things that can be done in this configuration file can be registered through the class where this annotation is located. Its several related annotations are also more important:

@Bean

Used to replace the < bean… > configuration in XML configuration files.

@ImportResource

If some cannot be configured through class registration, additional XML configuration files can be introduced through this annotation. Some old configuration files cannot be configured effectively through @Configuration

@Import

Configuration class files used to introduce one or more additional @Configuration decorations

@SpringBootConfiguration

It is another name for @Configuration in Spring Boot

3.

This is an annotation added by Spring 3.1 to replace the component-scan configuration in the configuration file and enable component scanning, that is, the @Component annotation under the package path is automatically scanned to register bean instances into the context.

Other notes

@ConfigurationProperties

Used to load additional configuration (such as .properties files), it can be used on the @Configuration annotation class or the @Bean annotation method.

@EnableConfigurationProperties

It is generally used in conjunction with the @ConfigurationProperties annotation to enable support for the @ConfigurationProperties annotation configuration bean.

@AutoConfigureAfter

Used in the automatic configuration class above, indicating that the automatic configuration class needs to be configured after the other specified automatic configuration class.

For example, the automatic configuration class of Mybatis needs to be after the automatic configuration class of the data source.

1
2
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MybatisAutoConfiguration {

@AutoConfigureBefore

This is the opposite of the use of the @AutoConfigureAfter annotation, indicating that the autoconfiguration class needs to be configured before the autoconfiguration class specified otherwise.

@RestController

It is a collection of @Controller and @ResponseBody, indicating that this is a controller bean, and the return value of the function is directly filled into the HTTP response body, which is a REST-style controller.

@Autowired

Automatically imported.

@PathVariable

Get the parameters.

@JsonBackReference

The @JsonBackReference and @JsonManagedReference in Jackson, as well as @JsonIgnore, are designed to solve the problem of infinite recursion caused by bidirectional references in objects. These annotations can be used in properties or corresponding get and set methods.

@JsonBackReference and @JsonManagedReference: These two annotations are usually paired and used in parent-child relationships. The properties of the @JsonBackReference annotation are ignored during serialization (i.e. the object is converted into json data) (i.e. the json data in the result does not contain the content of the property). The properties of the @JsonManagedReference annotation are serialized. During serialization, @JsonBackReference is equivalent to @JsonIgnore, and @JsonManagedReference can be absent. However, during deserialization (i.e. converting json data into objects), if there is no @JsonManagedReference, the attributes annotated with @JsonBackReference (ignored parent or child) will not be automatically injected; if there is @JsonManagedReference, the attributes annotated with @JsonBackReference will be automatically injected.

@RepositoryRestResourcepublic

Use with spring-boot-starter-data-rest.

@ResponseBody

Indicates that the return result of this method is directly written into the HTTP response body, which is generally used when obtaining data asynchronously and is used to build RESTful APIs. After using @RequestMapping, the return value is usually parsed as a jump path. After adding @responsebody, the return result will not be parsed as a jump path, but is directly written into the HTTP response body. For example, asynchronously obtaining json data, after adding @responsebody, json data will be returned directly. This annotation is generally used in conjunction with @RequestMapping.

@Controller

Used to define the controller class. In the spring project, the controller is responsible for forwarding the URL request sent by the user to the corresponding service interface (service layer). Generally, this annotation is in the class, and usually the method needs to be matched with the annotation @RequestMapping.

@RestController

Collection used to annotate control layer components (such as actions in struts), @ResponseBody and @Controller

@RequestMapping

Provides routing information that is responsible for mapping URLs to specific functions in the Controller.

@Repository

Use the @Repository annotation to ensure that DAO or repositories provide exception translation. The DAO or repositories classes modified by this annotation will be discovered and configured by ComponetScan, and there is no need to provide XML configuration items for them.

@Value

Inject the values of properties configured application.properties Spring boot. Example code:

@Value(value = “#{message}”)
private String message;

@Inject

Equivalent to the default @Autowired, but without the required attribute;

@Component

Refers to components in general. When components are not easy to categorize, we can use this annotation to label them.

@AutoWired

Automatically import dependent bean. ByType method. The configured bean is used to complete the assembly of properties and methods. It can annotate class member variables, methods and constructor functions to complete the work of automatic assembly. When (required = false) is added, no error is reported even if the bean cannot be found.

@Qualifier

When there are multiple beans of the same type, it can be specified with @Qualifier (“name”). Used in conjunction with @Autowired. The @Qualifier qualifier descriptor can not only be injected based on the name, but also has more fine grained control over how to select candidates. The specific usage is as follows:
@Autowired
@Qualifier(value = “demoInfoService”)
private DemoInfoService demoInfoService;

@RequestMapping

@RequestMapping (“/path”) indicates that the controller handles all URL requests for “/path”. RequestMapping is an annotation used to handle request address mapping, which can be used on classes or methods.
Used on classes, it means that all methods in the class that respond to requests use this address as the parent path. The annotation has six properties:
Params: Specifies that the request must contain some parameter values for this method to process.
Headers: Specifies that the request must contain some of the specified header values for this method to process the request.
Value: Specifies the actual address of the request, which can be in URI Template mode
Method: Specify the method type of the request, GET, POST, PUT, DELETE, etc
Consumes: Specify the submission content type (Content-Type) for processing requests, such as application/json, text/html;
Produces: specifies the content type to be returned, which is only returned if the specified type is included in the (Accept) type in the request header

@RequestParam

Used in front of method parameters.
@RequestParam
String a =request.getParameter(“a”)。

@PathVariable

Path variable. Such as
RequestMapping(“user/get/mac/{macAddress}”)
public String getByMacAddress(@PathVariable String macAddress){
//do something;

@ControllerAdvice

Contains @Component. Can be scanned to. Unified handling of exceptions.

@ExceptionHandler(Exception.class)

Used in the above method means to execute the following method when encountering this exception.

@Resource(name=”name”,type=”type”)

Default byName without the content in parentheses. Similar to @Autowired.

@Scope

It describes how the Spring container creates an instance of a bean, which has several possible values:

  1. Singleton: A Spring container can only have one instance of a bean, which is the default configuration of Spring, and the whole container shares one instance
  2. Prototype: Create a new instance of the bean each time it is called
  3. Request: Web project, to each http request a new Bean instance
  4. Session: In the web project, create a new Bean instance for each http Session
  5. GlobalSesion: This is only useful in portal applications. Create a new Bean instance for each global http session.

@PostConstruct

After adding JSR250 support, the method modified by the annotation will be executed after the constructor function is completed

@PreDestroy

After adding JSR250 support, the method modified by this annotation will be executed before the bean is destroyed

Meta annotation

Meta annotations are annotations of annotations, including @Retention, @Target, @Document, @Inherited

@Retention

@Retention (RetentionPolicy. SOURCE): Annotations only exist in the source code, not in the class bytecode file

@Retention (RetentionPolicy. CLASS): Default retention policy, annotations will exist in the class bytecode file, but cannot be obtained at runtime

@Retention (RetentionPolicy. RUNTIME): Annotations will exist in the class bytecode file and can be obtained by reflection at runtime

@Target: Define the target of the annotation

@Target (ElementType. TYPE)//Interface, class, enumeration, annotation
@Target (ElementType. FIELD)//Constants for fields and enumerations
@Target (ElementType. METHOD)//method
@Target (ElementType. PARAMETER)//method parameter
@Target (ElementType. CONSTRUCTOR)//constructor function
@Target (ElementType.LOCAL_VARIABLE)//local variable
@Target(ElementType.ANNOTATION_TYPE)//注解
@Target(ElementType.PACKAGE) ///包

@Documented

Indicates that the annotation will be included in javadoc

@Inherited

Subclasses can inherit the annotation from the parent class

Examples illustrate

We can define a new annotation through the above several annotations, such as

1
2
3
4
5
6
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Action {
String name;
}

In this way, we define a new annotation called Action, which has an attribute called name

Spring implements multi-threaded and concurrent programming through TaskExecutor. Use ThreadPoolTaskExecutor to implement a TaskExecutor based on thread pool. In actual development, tasks are generally non-hindered, that is, asynchronous, so we need to enable support for Asynchronous Tasks through @EnableAsync in the configuration class, and declare it as an Asynchronous Tasks by using the @Async annotation in the method of the actual executed Bean.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Configuration
@ComponentScan("com.wisely.highlight")
@EnableAsync
public class TaskExecutorConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor () {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);
taskExecutor.setMaxPoolSize(10);
taskExecutor.setQueueCapcity(25);
taskExecutor.initialize();
return taskExecutor;
}
}

By configuring the class above, all @Async-decorated classes or methods in the “com.wisely.highlight” package are asynchronous.

Spring Planning Tasks

First, annotate @EnableScheduling in the configuration class to enable support for scheduled tasks, and then annotate @Scheduled on the method to execute the scheduled task, declaring it to be a scheduled task.

Scheduled tasks supported by @Scheduled are divided into various types, including corn, fixDelay, fixRate, etc

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.wisely.highlight
@Service
public class ScheduledTaskService {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

@Scheduled (fixedRate = 5000)//Execute every five seconds
public void reportCurrentTime () {

}

@Scheduled (corn = "0 25 11 ?* *") // scheduled tasks, each executed at 11:28
public void fixTimeExecution () {

}
}

Support for scheduled tasks can be turned on via @EnableScheduling

1
2
3
4
5
6
@Configuration
@ComponentScan("com.wisely.highlight")
@EnableScheduling
public class TaskSchedulerConfig {

}

This way all classes under the com.wisely.highlight package will enable support for scheduled tasks

Implementation

1
2
3
4
5
public class Main {
public static void main (String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigAoolicationContext (TaskSchedulerConfig.class)
}
}

Reference article

https://zhuanlan.zhihu.com/p/57689422

https://blog.csdn.net/zsq520520/article/details/55261359

https://blog.csdn.net/qq_35357001/article/details/55505659

ExceptionHandler使用法简介