Gou Yingkui
Source:
Creditease Institute of Technology
In Spring Boot, a large number of tedious configurations in previous Spring projects are abandoned, and the principle of “convention is greater than configuration” is followed. By default configuration, the complexity of project construction is greatly reduced. Also in Spring Boot, a large number of annotations are used to make the code look more concise and improve the efficiency of development. These annotations include not only Spring Boot’s own annotations, but also some that are inherited from Spring.
This article summarizes some of the core annotations that are commonly used in Spring Boot projects and explains how they work in practical terms.
Item Configuration Annotations
1, @springBootApplication annotation
If you look at the source code, you can see that @SpringBootApplication is a composite annotation, including @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan.
The functions of these three annotations are:
-
@SpringBootConfiguration: Annotates the current class as a Configuration class. This annotation inherits from @Configuration. Instances of one or more methods declared in the current class tagged with the @bean annotation are included in the srping container, and the instance name is the method name.
-
EnableAutoConfiguration: this is an autoconfiguration annotation that will do some default configuration based on the component JAR we added. We added a POM dependency for the spring-boot-starter-web component JAR when we inweaved. This configuration will default springMVC and Tomcat.
-
@componentScan: Scans classes in the current package and its subpackages that are annotated by @Component, @Controller, @Service, and @repository and manages them in the Spring container. Configuration items in the XML configuration file equivalent to <context:component-scan>.
In most cases, the three annotations are used together, and based on best practices, the three annotations are wrapped as @SpringBootApplication annotations.
2, @ ServletComponentScan: Servlet, Filter, the Listener can directly through the @ WebServlet, @ WebFilter, @ WebListener annotation automatically register, so through annotations Servlet, interceptors, The listener function does not require additional configuration, so the implementation of the Filter is used in this phase, using this annotation.
3. @Mapperscan: Spring-boot supports an annotation of myBatis component. By specifying the path of myBatis interface class, you can complete the scanning of MyBatis interface.
It has the same function as the @mapper annotation, the difference is that the scan entry is different. @mapper needs to be added to every Mapper interface class. In most cases, the mapper interface is injected through the @MapPERScan annotation configuration path after the project directory is planned.
After adding myBatis corresponding build dependencies. You can use the annotation.
Take a closer look at the myBatis spring-boot-starter package, and you’ll find that myBatis has been wrapped here.
This is also a concept of Spring, not to repeat the wheel, integrate excellent resources into the Spring system.
4. Resource Import annotations: @importResource @import @propertysource These three annotations are used to Import custom configuration files.
@importResource (locations={}) Import other XML configuration files, you need to standard on the primary configuration class.
The @propertysource configuration file for the import property specifies the file path. This is equivalent to using spring’s < importResource /> tag to complete the import of the configuration item.
The @import annotation is a way to import a normal class into the Spring container for management
The controller layer
1. @Controller indicates that this class is a Controller class and is used in conjunction with @RequestMapping to intercept requests. If you do not specify the method of requesting the request, the default is to intercept GET and POST requests. The request is then forwarded to a view resolver after completion. But when most microservices are built, the front and back ends are separated. So the request back end only cares about the data processing, and if the back end returns JSON data, it needs to be completed with the @responseBody annotation.
An interface that only needs to return data requires three annotations, and most of the time we need to return data. This 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, @responseBody is no longer required in the data interface. More concise.
In the same case, @requestMapping (value=””,method= requestMethod.get), we need to specify how to request. This writing method will appear more complicated, so there are a few notes as follows.
Ordinary style | Rest style |
@ RequestMapping (value = “, “method = RequestMethod. GET) |
@ GetMapping (value = “”) |
@ RequestMapping (value = “, “method = RequestMethod. POST) |
@ PostMapping (value = “”) |
@ RequestMapping (value = “, “method = RequestMethod. PUT) |
@ PutMapping (value = “”) |
@ RequestMapping (value = “, “method = RequestMethod. DELETE) |
@ DeleteMapping (value = “”) |
These annotations are best practices for @RequestMapping(value=””,method= requestMethod.xxx). In order to make the code more concise.
@crossorigin: @crossorigin (Origins = “”, maxAge = 1000) This annotation can be enabled for the entire Controller configuration, or at the method level.
We used this annotation in the project to solve the cross-domain problem of the microserver accessing different spider nodes when doing scheduled task scheduling.
3. @autowired: This is one of the most familiar annotations. It is a spring autower. this annotation can be used on constructors, variable fields, methods, and annotation types. When we need to get a bean from the bean factory, Spring will automatically assemble elements in that bean marked @autowired for us.
4. @EnablCaching@EnableCaching: This annotation is the annotation-driven cache management feature of the Spring Framework. This annotation has been added since Spring version 3.1. This is equivalent to the Cache Manager tag in the Spring configuration file.
@requestMapping uses {} to define the url part of the variable. For example:
The variable name and regular expression can also be supported. The variable name is [regular expression].
Servcie layer annotation
1. @service: This annotation is used to mark components in the business layer. We will pass this annotation to the Spring container for classes that are processed by the business logic. The facets of the transaction are also configured at this level. When this annotation is not required. There is a component-specific annotation that we can entrust to the Spring container when we are not sure what it does.
@Resource: @Resource can be used to assemble beans, just like @Autowired can be used to annotate fields or methods. The @resource annotation is not provided by Spring, but belongs to the J2EE specification.
The difference is that @Resource matches beans by name and @Autowired matches beans by type by default.
Persistence layer annotations
@repository: @repository annotation classes act as DAO objects that manage objects that operate on the database.
In summary, @Component, @Service, @Controller, and @repository are Spring annotations that can be scanned by the Spring framework and injected into the Spring container for management
The @Component annotation is a generic annotation, and the other three annotations are extensions of this annotation with specific functionality.
Through the hierarchical management of these annotations, the request processing, obligation logic processing, database operation processing can be separated, for code decoupling, but also facilitate the maintenance and development of future projects.
If @Service, @Controller, or @Repository can be used in normal development, then @Component should not be used.
2. @Transactional: This annotation declares transactions that can be added to classes or methods.
There is no need to configure transaction management separately in Spring Boot. In general, we will add transaction annotations to the Servcie layer to start transactions. Note that transactions can only be opened on public methods. And the rollback conditions for the major transaction aspect. Normally when we configure rollbackfor Exception, catching an exception in a method invalidates the transaction aspect configuration.
Other related notes
-
@ControllerAdvice and @RestControllerAdvice: Usually used together with @ExceptionHandler, @initBinder, and @ModelAttribute.
-
@ControllerAdvice and @ExceptionHandler work together for uniform exception handling.
-
@RestControllerAdvice is a collection of @ControllerAdvice and @responseBody that returns data in JSON format for exceptions.
The following is a uniform processing of data exception returns.
Here is a summary of the usual use of some annotations, and application instructions. There are other deeper knowledge still need to continue to learn in the subsequent use.
Reference documentation
-
https://docs.spring.io/spring-boot/docs/2.1.x/reference/html/
-
https://spring.io/projects/spring-boot/