Spring Boot (16): Introduction and use of common annotations in Spring Boot

1. Project configuration notes

1、@SpringBootApplication

This is a combination of annotations including @SpringBootConfiguration, @EnableAutoConfiguration and @ComponentScan annotations.

(1) @SpringBootConfiguration inherits from @Configuration. For developers familiar with spring, this annotation is used when the current class is a configuration class, and will include one or more instances of methods declared in the current class marked with the @Bean annotation. into the spring container, and the instance name is the method name.

(2) @EnableAutoConfiguration This annotation is the magic of springboot's automatic configuration. Mainly through this annotation, all bean definitions that meet the automatic configuration conditions can be loaded into the spring container. For example, according to spring-boot-starter-web, to determine whether your project needs to add webmvc and tomcat, it will automatically help you Configure the default configuration required in the web project. When you need to exclude some classes that do not need automatic configuration, you can use exclude to exclude them.

(3) @ComponentScan will scan the classes marked by @Component, @Controller , @Service, @Repository and other annotations under the current package and its subpackages   and incorporate them into the spring container for management

2 、 @ MapperScan

Springboot supports an annotation of the mybatis component. By specifying the path of the mybatis interface class through this annotation, the scanning of the mybatis interface can be completed.

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

After adding the corresponding component dependencies of mybatis. You can use this annotation.

3. Resource import annotation

The three annotations @ImportResource, @Import, and @PropertySource are all used to import some custom configuration files.

@ImportResource (locations={}) Import other xml configuration files, which need to be standard on the main configuration class.

Import the property's configuration file  @PropertySource to specify the file path, which is equivalent to using spring's <importresource/> tag to complete the introduction of configuration items.

The @import annotation is a way to import common classes into the spring container for management

Second, the controller layer

1、@Controller和@RestController

@RestController is an annotation added after spring 4. Originally, returning json in @Controller requires @ResponseBody to cooperate. If you directly replace @Controller with @RestController, you do not need to configure @ResponseBody again, and json format is returned by default. The @Controller is used to create an object that handles http requests, and is generally used in conjunction with @RequestMapping.

2 、 @ CrossOrigin

@CrossOrigin(origins="",maxAge=1000)

This annotation is mainly to solve the problem of cross-domain access. This annotation can enable cross-origin for the entire controller configuration, or it can be enabled at the method level.

We use this annotation in the project to solve the cross-domain problem that microservices cannot access spider nodes when scheduling scheduled tasks.

3、@Autowired

Autowiring.

When we need to get a bean from the bean factory, spring will automatically wire the element marked @Autowired in the bean for us.

4、@EnableCaching

This annotation is an annotation-driven cache management feature in the spring framework. The role is equivalent to the cache manager tag in the spring configuration file.

5、@RequestMapping

An annotation for handling request address mapping, which can be used on classes and methods. Used on a class, indicating that all methods in the class that respond to requests use this address as the parent path.

Common properties:

(1) value: specify the actual address of the request, the specified address can be in URI Template mode;

(2) method: specify the method method of the request, GET, POST, PUT, DELETE, etc.;

(3) consumes: specifies the content-type (content-type) of the submitted request, such as application/json, text/html;

(4) produces: specifies the returned content type, which is only returned when the (Accept) type in the request header contains the specified type;

(5) params: Specify that the request must contain certain parameter values ​​before this method can process it.

(6) headers: The specified request must contain certain specified header values ​​in order for this method to process the request.

Commonly used are value and method.

Its simplified annotations are:

@GetMapping is equivalent to @RequestMapping(method = RequestMethod.GET)
@PostMapping is equivalent to @RequestMapping(method = RequestMethod.POST)
@PutMapping is equivalent to @RequestMapping(method = RequestMethod.PUT)
@DeleteMapping is equivalent to @RequestMapping(method = RequestMethod. DELETE)
@PatchMapping is equivalent to @RequestMapping(method = RequestMethod.PATCH)

6、@RequestBody和@ResponseBody

The @RequestBody annotation allows request parameters to be in the reqeust body, often combined with front-end POST requests for front-end and back-end interactions.

The @ResponseBody annotation supports putting the parameters in the reqeust body, usually returning json format to the front end.

7、@PathVariable、@RequestParam、@RequestAttribute

@PathVariable is used to receive parameters, such as /path/001, which can receive 001 as a parameter

@GetMapping("/path/{id}")
public String PathVariable(@PathVariable("id")String id){
    return "id:"+id;
}

@RequestParam is used to receive parameters in the URL, such as /param?id=001, which can receive 001 as a parameter

@GetMapping("/param")
public String param(@RequestParam("id")String id){
    return "id:"+id;
}

@RequestAttribute is used to access pre-existing request attributes created by filters or interceptors, and is equivalent to request.getAttrbute().

@GetMapping("/req/attr")
public String reqAttr(@RequestAttribute("id")String id){
    return "id:"+id;
}

8 、 @ ModelAttribute

Mainly to bind request parameters to specified objects, this annotation can be used on methods and parameters.

When applied to parameters, the parameters passed by the client will be injected into the specified object by name, and the object will be automatically added to the modelMap, which is convenient for the view layer to use;

When applied to the method, it will be executed before each method marked with @RequestMapping. If there is a return value, the return value will be automatically added to the ModelMap;

Since the front-end and back-end are now developed separately, annotations are relatively rarely used, but some additional operations are required before each request. Using this annotation is still an option, such as unified business verification, etc., but you need to pay attention when using this annotation to implement similar functions. When using asynchronous calls, such as callable or DeferredResult, the annotated method will be executed twice, because asynchronous When requesting, another thread is suspended to re-execute. For interceptors configured, their execution order is:

preHandle ---->
afterConcurrentHandlingStarted ----> 
Controller---->
preHandler----> 
postHandler ----> 
afterCompletion

3. Service layer annotations, persistence layer annotations

1、@Component、@Service、@Repository

These three all declare a singleton bean class and incorporate it into the spring container, and the latter two are actually inherited from @Component.

(1) @Component is the most common component that can be injected into the spring container for management.

Through the hierarchical management of this annotation, request processing, business logic processing, and database operation processing can be separated, decoupling the code, and facilitating the maintenance and development of future projects.

So in normal development, if you can use one of @Service, @Controller, @Repository to mark the location of this class, don't use @Component to mark it.

(2) @Repository acts on the persistence layer

(3) @Service acts on the business logic layer

Usually, when some classes cannot really use @service or @Component, the annotation uses @Component, such as Redis configuration class.

2、@Transational

Transactions can be declared through this annotation, which can be added to classes or methods.

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

 

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324192484&siteId=291194637