Programmer’s Notes-Common Annotation of ——springboot

  springboot

In spring boot, a lot of complicated configurations in spring’s previous projects are abandoned and followedContract is greater than configurationBy default configuration, it greatly reduces the complexity of project construction. Also in spring boot, the use of a large number of annotations makes the code look more concise and improves the efficiency of development. These comments include not only spring boot’s own, but also some inherited from spring.

    本文中将spring boot项目中常用的一些核心注解归类总结,并结合实际使用的角度来解释其作用。

Project configuration comments


1. @SpringBootApplication comments

Looking at the source code, it can be found that @SpringBootApplication is a compound annotation, including @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan.

The functions of these three annotations are:

  • @SpringBootConfiguration: Indicates that the current class is a configuration class. This annotation is inherited from @Configuration. One or more ins tances of methods marked with @Bean annotations declared in the current class are included in the srping container, and the instance name is the method name.
  • @EnableAutoConfiguration: it is an annotation of automatic configuration. this annotation will complete some default configurations according to the co mponent jar that we added. when we do micro-service, we will add the pom dependency of the component jar, spring-boot-starter-web. in this way, springmvc and tomcat will be configured by default.
  • @ComponentScan: scan the classes marked by @ components, @Controller, @Service, @Repository annotation under the current package and its sub-packages and bring them into the spring container for management. Configuration items in xml configuration files equivalent to < context:component-scan >.

图片描述

In most cases, these three annotations will be used at the same time. Based on best practices, these three annotations will be packaged as @SpringBootApplication annotations.

2. @ServletComponentScan:Servlet, Filter, Listener can be automatically registered directly through @WebServlet, @WebFilter, and @WebListener annotations. thus, the functions of servlet, interceptor, and listener can be annotated without any other configuration. therefore, the implementation of filter is used in this phase, and this annotation is used.

3. @MapperScan:spring-boot supports an annotation of the myatis component. by specifying the path of the myatis interface class through this annotation, scanning of the myatis interface can be completed.

It has the same function as the @mapper annotation, except that the scanning entrance is different. @mapper needs to be added to each mapper interface class. Therefore, in most cases, mapper interface injection is completed through the @MapperScan annotation configuration path after the project directory is planned.

After adding the corresponding build dependency for mybatis. You can use the annotation.

图片描述

Further examination of the myatis-spring-boot-starter package shows that myatis has been packaged here.

This is also an idea of spring. It does not make wheels repeatedly and integrates excellent resources into spring’s system.

图片描述

4. Resource Import Notes: @ Import Resource @ Import @ Propertysource These three notes are used to import some customized configuration files.

@ImportResource(locations={}) Imports other xml configuration files, which require standards on the main configuration class.

The configuration file @PropertySource for importing property specifies the file path, which is equivalent to using spring’s < importresource/ > tag to complete the introduction of configuration items.

@import Annotation is a management tool that can import common classes into spring containers.

Controller layer


1. @Controller indicates that this class is a controller class, and @RequestMapping is used to intercept requests. If the method is not specified, get and post requests will be intercepted by default. This way, the request will complete and go to a view parser. However, when most micro services are built, the front and back ends will be separated. Therefore, the request back-end only focuses on data processing. If the back-end returns json data, it needs to be completed with @ResponseBody annotation.

Such an interface that only needs to return data needs 3 annotations to complete, most of the time we need to return data. It is also based on best practices, so the three annotations are further integrated.

@RestController is a combination of @Controller and @ResponseBody. when a class is annotated with @RestController, there is no need to add @ResponseBody to the data interface. More concise.

In the same situation. @ requestmapping (value = “”,method = requestmethod.get), we all need to specify the request method. This kind of writing will appear more complicated, so I have the following comments.

图片描述
These comments are best practices for @ requestmapping (value = “”,method = requestmethod.xxx). In order to make the code more concise.

2. @ crossorigin: @ crossorigin (origin = “”,maxage = 1000) this annotation is mainly to solve the problem of cross-domain access. This annotation can enable cross-domain for the entire controller configuration or can be enabled at the method level.

We use this annotation in the project to solve the cross-domain problem when micro-service accesses different spider nodes when scheduling scheduled tasks.

3. @ autowire: this is the most familiar annotation, which is spring’s automatic assembly. this annotation can be used in constructors, variable fields, methods, and annotation types. When we need to get a bean from the bean factory, Spring will automatically assemble the element marked @Autowired in the bean for us.

4. @EnablCaching@EnableCaching: this annotation is an annotation-driven cache management function in the spring framework. This comment has been added since spring version 3.1. Its function is equivalent to cache manager label in spring configuration file.

5. @PathVariable: path variable annotation, {} is used in @RequestMapping to define the variable name of the url part, such as:

图片描述

You can also support variable name plus regular expression, variable name: [regular expression].

图片描述

Servcie layer annotation


1. @Service: This annotation is used to mark the components of the business layer. We will add this annotation to all classes handled by the business logic to the spring container. The tangent plane of the transaction is also configured at this layer. It is not necessary to use this annotation. There is a comment that refers to components in general. When we are not sure of the specific function, we can entrust the spring container with the comment that refers to components in general.

2. @ resource: @ resource and @ autowire can be used to assemble bean, and can be labeled on fields or methods. @resource annotation is not provided by spring but belongs to J2EE specification.

The difference between the two is that the matching method is somewhat different. @Resource matches beans by name by default and @ autowire matches beans by type by default.

Persistence annotation


1. @ Repository: @ Repository annotation class is used as DAO object to manage the objects of operation database.

In general, @ component, @ service, @ controller, @ repository are spring annotations that can be scanned by the spring framework and injected into the spring container for management.

@Component is a general annotation, and the other three annotations are extensions of this annotation and have specific functions.

Through the hierarchical management of these annotations, request processing, obligation logic processing and database operation processing can be separated to decouple the codes and facilitate the maintenance and development of future projects.

Therefore, in normal development, if we can use one of @ service, @ controller, @ repository to mark the location of this class, we should not use @Component to mark it.

2. @Transactional: Through this annotation, transactions can be declared and added to classes or methods.

In spring boot, there is no need to separately configure transaction management. Generally, we will add transaction annotations to the servcie layer to open the transaction. Note that the transaction can only be opened on the public method. And the rollback condition of the main transaction plane. Normally when we configure rollbackfor exception, if an exception is caught in the method, the transaction plane configuration will be invalidated.

Other relevant comments


  • @ControllerAdvice and
    @ restcontroleradvice: usually used with @ExceptionHandler. @InitBinder, @ModelAttribute.
  • @ControllerAdvice and @ExceptionHandler cooperate to complete unified exception interception processing.
  • @RestControllerAdvice is @ControllerAdvice and
    The collection of @ResponseBody can return exceptions to data in json format.

The following is the unified treatment for abnormal data return.

图片描述

This is a summary of some annotations used in ordinary times and their application instructions. There are other deeper knowledge that needs to be further studied in the subsequent use.

Reference documents:

https://docs.spring.io/spring …

https://spring.io/projects/sp …

Author: Gou Yingkui

Yixin Institute of Technology