Spring Boot Notes: family bucket quick pass

The course will Boot Spring annotations to be involved in all sort, commonly used in the development process and the corresponding Annotation introduced sample code. Help developers a unified, standardized, comprehensive study and master the use of the Spring Framework Annotations.

Spring Boot Notes: family bucket quick pass

 

1, Spring Web MVC and Spring Bean notes

1-1, Spring Web MVC comment

1-1-1、@RequestMapping

The main purpose is to Web @RequestMapping annotation request with the request class mapping method. Spring MVC and Spring WebFlux are to provide support for @RequestMapping annotated by RquestMappingHandlerMapping and RequestMappingHndlerAdapter two classes.

@RequestMapping annotation request processing method for processing the request class to mark; @RequestMapping annotation configuration has the following six properties:

  • value: or a request URL mapping alias
  • method: HTTP-compatible method name
  • params: The filtered presence of the request, or a default parameter value of the HTTP
  • header: the request according to HTTP Header presence filtration, or the default value
  • consume: setting HTTP request body allowed media types
  • product: allowing the media type used in the HTTP response body

Note: Before using @RequestMapping, request processing also require the use @Controller class labeled or @RestController

Below are two examples of the use @RequestMapping:

Spring Boot Notes: family bucket quick pass

 

@RequestMapping class may also be labeled, value such class processing method when mapping the path request, will automatically set the class @RequestMapping stitching path prior to mapping method, as follows:

Spring Boot Notes: family bucket quick pass

 

1-1-2、@RequestBody

@RequestBody parameter list using processing request method, it can request parameters bound to an object in the body, the body of the request parameter is transmitted through HttpMessageConverter, according to the request body parameters attribute names and object names match and bind values. In addition, the request may be verified by the body parameters @Valid annotation. Here is an example of a use @RequestBody:

Spring Boot Notes: family bucket quick pass

 

1-1-3、@GetMapping

@GetMapping annotation for processing HTTP GET request, and the request is mapped to a specific treatment method. Specifically, @ GetMapping is a combination of notes, which is equivalent to a shortcut @RequestMapping (method = RequestMethod.GET) of. The following example is to use a @GetMapping:

Spring Boot Notes: family bucket quick pass

 

1-1-4、@PostMapping

@PostMapping annotation for processing HTTP POST request, and the request is mapped to a specific treatment method. @PostMapping and @GetMapping just as a combination of notes, which is equivalent to a shortcut @RequestMapping (method = HttpMethod.POST) of. Here is an example of using @PostMapping:

Spring Boot Notes: family bucket quick pass

 

1-1-5、@PutMapping

@PutMapping annotation for processing an HTTP PUT request, and the request is mapped to a specific treatment method, @ PutMapping annotation is a combination, the equivalent shortcut @RequestMapping (method = HttpMethod.PUT) a. Here is an example of using @PutMapping:

Spring Boot Notes: family bucket quick pass

 

1-1-6、@DeleteMapping

@DeleteMapping annotation for processing HTTP DELETE request and maps the request to delete process. @DeleteMapping annotation is a combination, which is equivalent to a shortcut @RequestMapping (method = HttpMethod.DELETE) a. Here is an example of using @DeleteMapping:

Spring Boot Notes: family bucket quick pass

 

1-1-7、@PatchMapping

@PatchMapping annotation for processing HTTP PATCH request and the request is mapped to a corresponding processing method. @PatchMapping equivalent shortcut @RequestMapping (method = HttpMethod.PATCH) of. The following is a simple example:

Spring Boot Notes: family bucket quick pass

 

1-1-8, @ ControllerAdvice

@ControllerAdvice @Component annotation is an extension of annotation, Spring automatically scans and detects @ControllerAdvice marked classes. @ControllerAdvice needs and @ ExceptionHandler, @ InitBinder and @ModelAttribute notes with the use of information is mainly used to handle exceptions thrown by the controller. First, we need to define a @ControllerAdvice be marked classes in the class definition of a particular exception processing method for, using labeled @ExceptionHandler annotation. Further, when necessary, may be used globally @InitBinder disposed in the class, @ModelAttribute view parameter associated with the configuration can also be used. @ControllerAdvice use annotations, you can quickly create a unified, custom exception handling classes. The following is a sample code @ControllerAdvice of:

Spring Boot Notes: family bucket quick pass

 

1-1-9、@ResponseBody

@ResponseBody controller automatically return value is written to the HTTP response. In particular, @ ResponseBody annotation can be used in the class @Controller comment tag. If the tag @RestController class, the method does not require tagging @ResponseBody annotations. @RestController equivalent @Controller and @ResponseBody combination of notes. Here is an example of the use of annotation:

Spring Boot Notes: family bucket quick pass

 

1-1-10、@ExceptionHandler

@ExceptionHander annotation method for processing a particular type of exception thrown for a class label. When the process controller throws an exception, Spring automatically captures abnormal, and the abnormality information transmission method to capture the annotated @ExceptionHandler. Here is an example of the use of annotation:

Spring Boot Notes: family bucket quick pass

 

1-1-11, @ ResponseStatus

@ResponseStatus annotation may request tagging approach. Using this annotation, you can specify the desired response HTTP STATUS. In particular, we can use the HttpStauts classes annotated value of the property assignment. The following is an example of using annotations @ResponseStatus:

Spring Boot Notes: family bucket quick pass

 

1-1-12, @ PathVariable

@PathVariable annotation method is to bind the parameters to the template variables in the request URI. URI template variables can be specified by @RequestMapping notes, annotations and then use @PathVariable bind method parameters to the template variables. In particular, @ PathVariable annotation allows us to use the name attribute to value or an alias for parameter. The following is an example of this use annotation:

Spring Boot Notes: family bucket quick pass

 

Template variable names need to use the "{}" wrapped, if the method name is consistent with the URI template parameter variable name, can be omitted in the @PathVariable aliased. The following is an example of a shorthand:

Spring Boot Notes: family bucket quick pass

 

Tip: If the argument is a non-essential, optional items, you can set require = false in the @PathVariable

1-1-13、@RequestParam

@RequestParam annotation is used to pass parameters and the parameters of the method bound Web request. Use @RequestParam can easily access the HTTP request parameter values. The following is an example of the annotation using the code:

Spring Boot Notes: family bucket quick pass

 

Other properties of the annotation @PathVariable configured in the same configuration, in particular, if the passed parameter is null, a default value may be set by defaultValue. Sample code is as follows:

Spring Boot Notes: family bucket quick pass

 

1-1-14、@Controller

@Controller is an extension @Component annotation, Spring scan and automatically configure the annotation category is marked. This annotation is used to mark Spring MVC controller. The following sample code is annotated with this:

Spring Boot Notes: family bucket quick pass

 

1-1-15、@RestController

@RestController been introduced in Spring 4.0, which is a specific controller annotations. This annotation is equivalent to the shortcut @Controller and @ResponseBody. When this annotation, annotation @ResponseBody not need to use the method. The following sample code is annotated with this:

Spring Boot Notes: family bucket quick pass

 

01.01.16, @ ModelAttribute

This annotation can be accessed through the model index name already exists in the controller model. Here is a simple example of using this annotation:

Spring Boot Notes: family bucket quick pass

 

Like @PathVariable and @RequestParam notes, if the parameter name and model have the same name, you do not need to specify the index name, abbreviated example:

Spring Boot Notes: family bucket quick pass

 

In particular, if a method for tagging @ModelAttribute, Spring return value will be bound to the specific Model. Examples are as follows:

Spring Boot Notes: family bucket quick pass

 

Before calling a specific treatment method Spring, all methods are marked @ModelAttribute notes will be executed.

01.01.17, @ CrossOrigin

@CrossOrigin request for comment or request handler class approach to provide support for cross-domain calls. If we mark this annotation class, then all methods in the class will get the ability to support cross-domain. The benefits of using this annotation can fine-tune the cross-domain behavior. An example of using annotations as follows:

Spring Boot Notes: family bucket quick pass

 

1-1-18, @ Init Binder

The method of labeling the initialization WebDataBinider @InitBinder for annotation, the method is used to form a data transfer Http request is processed, such as the time format, string processing. The following are examples of using this annotation:

Spring Boot Notes: family bucket quick pass

 

1-2, Spring Bean notes

In this section, related mainly include four Spring Bean annotations and their use.

1-2-1、@ComponentScan

Spring @ComponentScan annotation for a package configuration to be scanned to be annotated based annotation component is located. Path packet may be configured to scan by configuring its properties or basePackages value attribute. value property is basePackages alias. Usage of this comment is as follows:

Spring Boot Notes: family bucket quick pass

 

1-2-2、@Component

@Component annotations used to annotate a normal component class, it is not clear scope of business, just notice this Spring is annotated classes need to be incorporated into the Spring Bean container and management. Example of use of this annotation is as follows:

Spring Boot Notes: family bucket quick pass

 

1-2-3、@Service

@Service @Component annotation is an extension of (a special case), it is used for labeling business logic classes. And @Component notes as being marked this class notes, will be automatically managed by Spring. Here is an example using @Service annotation:

Spring Boot Notes: family bucket quick pass

 

1-2-4、@Repository

@Repository annotation is @Component extending annotated, as in @Component annotations, annotation labeled this class is automatically manage Spring, @ Repository annotation data for labeling DAO layer persistent class. Usage of this comment is as follows:

Spring Boot Notes: family bucket quick pass

 

2, Spring Dependency Inject annotation and Bean Scops

2-1, Spring DI notes

2-1-1、@DependsOn

@DependsOn annotation can configure the Spring IoC container before initiating a Bean, Bean initialize other objects. This is annotated with the following sample code:

Spring Boot Notes: family bucket quick pass

 

2-1-2、@Bean

Notes @Bean main role is to inform the Spring, is marked by this annotation class will need to be incorporated into the management Bean plant. @Bean annotation usage is very simple, here, highlighting @Bean annotation usage and destroyMethod of initMethod. Examples are as follows:

Spring Boot Notes: family bucket quick pass

 

2-2, Scops comment

2-2-1、@Scope

@Scope annotation can be used to define the scope @Component scope and class labels marked @Bean class. @Scope defined range of action has: singleton, prototype, request, session, globalSession or other custom range. Here is an example to explain prototype. When a Spring Bean is declared as the prototype (prototype model), in each requires the use of such time, Spring IoC container will change to initialize a new instance of the class. When defining a Bean, Bean scope attribute may be provided as prototype: scope = "prototype", @Scope annotation may also be used provided, as follows:

@Scope(value=ConfigurableBeanFactory.SCOPE_PROPTOTYPE)

We will be given below of two different ways to use the @Scope annotation, the following sample code:

Spring Boot Notes: family bucket quick pass

 

2-2-2, @ Scope singleton

When the scope is set to @Scope Singleton, it was noted in the comments in this class will only be initialized once Spring IoC container. By default, Spring IoC container class instances are initialized singleton. The same principle, this case there are two configurations, the following sample code:

Spring Boot Notes: family bucket quick pass

 

3, container configuration annotations

3-1、@Autowired

@Autowired annotation tag dependencies for Spring and injected to be parsed. This annotation can act on the constructors, fields and setter methods.

3-1-1, acting constructor

The following are examples of the use of labeled @Autowired annotation constructor:

Spring Boot Notes: family bucket quick pass

 

3-1-2, acting on a setter method

The following sample code is denoted @Autowired annotation setter methods:

Spring Boot Notes: family bucket quick pass

 

3-1-3, acting on the field

@Autowired annotation label field is the most simple, requiring only the addition of this annotation to the corresponding fields in the sample code is as follows:

Spring Boot Notes: family bucket quick pass

 

3-2、@Primary

When the system needs to be configured with the same type of a plurality of bean, @ Primary define priorities in the Bean. The following example will be given of a code to illustrate this feature:

Spring Boot Notes: family bucket quick pass

 

Output:

this is send DingDing method message.

3-3, @ PostConstruct and @PreDestroy

Notably, these annotations are not Spring, JSR-250 are derived from the two annotations, located in the common-annotations.jar. @PostConstruct annotation method before Spring Bean is initialized to be executed for the label. Bean labeling method to be executed before being destroyed @PreDestroy for comment. The following are specific examples of the code:

Spring Boot Notes: family bucket quick pass

 

3-4、@Qualifier

When a plurality of the same type exist in the system Bean, @ Autowired dependency injection is performed when the implementation class do not know which one to select for the injection. At this point, we can use annotations to fine-tune @Qualifier, @Autowired help select the correct dependencies. The following is a code sample on this annotation:

Spring Boot Notes: family bucket quick pass

 

4, Spring Boot comment

4-1、@SpringBootApplication

@SpringBootApplication annotation is a quick annotation configuration, it being marked class may define one or more Bean, Bean and automatically trigger auto-configuration and auto scan assembly. This annotation is equivalent to a combination of @ Configuration, @ EnableAutoConfiguration and @ComponentScan of. In the main class Spring Boot application, use this annotation. Sample code is as follows:

@SpringBootApplication
public class Application{
public static void main(String [] args){
SpringApplication.run(Application.class,args);
}
}

4-2、@EnableAutoConfiguration

@EnableAutoConfiguration annotation for notifying Spring, according to the current class path dependencies introduced automatically configured with these configuration items related dependencies.

4-3、@ConditionalOnClass与@ConditionalOnMissingClass

These two conditions annotation notes belong to the class, judge them as a basis to decide whether to perform some configuration according to the presence or absence of a class. The following is a simple example code:

@Configuration
@ConditionalOnClass(DataSource.class)
class MySQLAutoConfiguration {
//...
}

4-4、@ConditionalOnBean与@ConditionalOnMissingBean

These two conditions belong to the object annotation notes, as a basis to decide whether or not to perform certain configuration method based on the presence or absence of an object. Sample code is as follows:

@Bean
@ConditionalOnBean(name="dataSource")
LocalContainerEntityManagerFactoryBean entityManagerFactory(){
//...
}
@Bean
@ConditionalOnMissingBean
public MyBean myBean(){
//...
}

4-5、@ConditionalOnProperty

@ConditionalOnProperty annotations meets the basic requirements according to the Spring configuration file configuration items, to decide whether or not to execute its methods are marked. Sample code is as follows:

@Bean
@ConditionalOnProperty(name="alipay",havingValue="on")
Alipay alipay(){
return new Alipay();
}

4-6、@ConditionalOnResource

This annotation is used when detecting the presence of a profile so that, by its method of labeling is triggered, the following sample code for this annotation is used:

@ConditionalOnResource(resources = "classpath:website.properties")
Properties addWebsiteProperties(){
//...
}

4-7、@ConditionalOnWebApplication与@ConditionalOnNotWebApplication

Both annotations are used to determine whether the current application is a Web application. If the current application is a Web application, use the Spring WebApplicationContext, and define the life cycle of their sessions. The following is a simple example:

@ConditionalOnWebApplication
HealthCheckController healthCheckController(){
//...
}

4-8、@ConditionalExpression

This annotation allows us to control more fine-grained expression-based configuration conditions. When the expression a condition is met or when the expression is true, will be marked this execution method comment.

@Bean
@ConditionalException("${localstore} && ${local == 'true'}")
LocalFileStore store(){
//...
}

4-9、@Conditional

@Conditional annotation can control is more complex configurations conditions. Spring conditions when the built-in control annotation does not meet the application requirements, you can use this annotation to define custom control conditions, in order to meet the requirements of custom. The following is a simple example of the use of annotation:

@Conditioanl(CustomConditioanl.class)
CustomProperties addCustomProperties(){
//...
}

to sum up

  • The course summarizes the common use various types of annotations Spring Boot, the unified so that we can have a comprehensive understanding of the Spring Boot common comment. For reasons of space, on Spring Boot unusual number of notes, will share in the next supplement and explanation.

Guess you like

Origin www.cnblogs.com/huangjinyong/p/12461950.html