This article will take about 9.2 minutes to read.

Author: Tan Chaohong

Link: https://www.ramostear.com/

1. Spring Web MVC with Spring Bean annotations

1-1, Spring Web MVC annotations

In the 1-1-1 s, @ RequestMapping

The main purpose of the @RequestMapping annotation is to map Web requests to methods in the request processing class. Spring MVC and Spring WebFlux through RquestMappingHandlerMapping and RequestMappingHndlerAdapter two classes to provide support for @ RequestMapping annotations.

The @requestMapping annotation annotates the request handling methods in the request handling class. The @requestMapping annotation has the following six configuration attributes:

  • Value: request URL of the mapping or its alias
  • Method: indicates the HTTP compatible method name
  • Params: Filters requests based on the presence, default, or value of HTTP parameters
  • Header: Filters requests based on the existence, default, or value of HTTP headers
  • Consume: Sets the type of media allowed in the body of an HTTP request
  • Product: Media type allowed in the HTTP response body
Tip: Before using @requestMapping, the request processing class also needs to be marked with @Controller or @RestController
Here are two examples of using @requestMapping:
@requestMapping can also mark a class, so that when a method in a class maps the request path, it will automatically concatenate the value set in @RequestMapping to the value set in the method before the mapping path, as follows:


In the 1-1-2 s, @ RequestBody

The @requestbody is used in the parameter list of the processing request method to bind the parameters in the RequestBody to an object. The RequestBody parameters are passed through HttpMessageConverter, matching and binding values based on the parameter names in the RequestBody to the attribute names of the object. In addition, parameters in the request body can be validated using the @valid annotation. Here is an example using @requestBody:

In the 1-1-3 s, @ GetMapping

The @getMapping annotation is used to process HTTP GET requests and map requests to specific processing methods. Specifically, @getMapping is a composite annotation that is equivalent to a shortcut to @requestMapping (method= requestMethod.get). Here is an example of @getMapping in use:

In the 1-1-4 s, @ PostMapping

The @postMapping annotation is used to process HTTP POST requests and map requests to specific processing methods. @postMapping, like @getMapping, is a composite annotation that works as a shortcut to @requestMapping (method= httpmethod.post). Here is an example using @postMapping:

In the 1-1-5 s, @ PutMapping

The @putMapping annotation is used to process HTTP PUT requests and map the requests to specific processing methods. The @putMapping annotation is a composite annotation that is equivalent to a shortcut to @RequestMapping(Method = httpMethod.put). Here is an example of using @putMapping:

In the 1-1-6 s, @ DeleteMapping

The @deletemapping annotation is used to process HTTP DELETE requests and map them to DELETE methods. @deletemapping is a composite annotation that is equivalent to a shortcut to @requestMapping (method= httpmethod.delete). Here is an example of using @deletemapping:

In the 1-1-7 s, @ PatchMapping

The @PatchMapping annotation is used to process HTTP PATCH requests and map the requests to corresponding processing methods. PatchMapping is a shortcut to @requestMapping (method= httpmethod.patch). Here is a simple example:

In the 1-1-8 s, @ ControllerAdvice

@ControllerAdvice is an extension of the @Component annotation, and Spring automatically scans and detects classes flagged by @ControllerAdvice. @ControllerAdvice is used with @ExceptionHandler, @initBinder, and @ModelAttribute annotations to handle exceptions thrown by controllers. First, we need to define a class annotated by @ControllerAdvice, in which we define a method to handle the specific exception and mark it with the @ExceptionHandler annotation.
In addition, @initBinder can be used to configure classes globally when necessary, and @ModelAttribute can be used to configure view-specific parameters. Using the @controllerAdvice annotation, you can quickly create unified, custom exception handling classes. Here is an example code that uses @controllerAdvice:

In the 1-1-9 s, @ ResponseBody

@responseBody automatically writes the return value of the method in the controller to the HTTP response. Specifically, the @responseBody annotation can only be used in a class marked by the @Controller annotation. If you are in a class marked by @RestController, the method does not need to be annotated with the @responseBody annotation. @restController is kind of a combination annotation of @Controller and @responseBody. Here is an example of using this annotation:

In the 1-1-10 s, @ ExceptionHandler

The @ExceptionHander annotation is used to annotate methods that handle exceptions thrown by a particular type of exception class. When a method in a controller throws an exception, Spring automatically catches the exception and passes the caught exception information to the method annotated by @ExceptionHandler. Here is an example of using this annotation:

In the 1-1-11 s, @ ResponseStatus

The @responseStatus annotation annotates the request handling method. Using this annotation, you can specify the HTTP STATUS required for the response. In particular, we can assign the value attribute of the annotation using the HttpStauts class. Here is an example using the @responseStatus annotation:

In the 1-1-12 s, @ PathVariable

The @pathVariable annotation binds parameters in a method to template variables in the request URI. You can specify the template variables of the URI using the @requestMapping annotation, and then bind the parameters in the method to the template variables using the @pathVariable annotation. In particular, the @pathVariable annotation allows us to alias a parameter using the value or name attribute. Here is an example of using this annotation:
Template variable names need to be wrapped with “{}”. If the method parameter name is the same as the URI template variable name, the alias definition can be omitted in @pathVariable. Here is an example of a shorthand:
Tip: If the argument is an optional, optional option, set require = false in @pathVariable

In the 1-1-13 s, @ RequestParam

The @requestParam annotation is used to bind the parameters of a method to the parameters passed in the Web request. You can easily access the values of HTTP request parameters using @requestParam. Here is an example of code that uses this annotation:
The other attributes of this annotation are configured the same as @pathvariable, in particular, a defaultValue can be set using defaultValue if the parameter passed is empty. Example code is as follows:

In the 1-1-14 s, @ Controller

The @Controller is an extension of the @Component annotation, and Spring automatically scans and configures the classes annotated by the annotation. This annotation is used to annotate the Spring MVC controller. Here is sample code that uses this annotation:

In the 1-1-15 s, @ RestController

The @restController annotation, introduced in Spring 4.0, is a controller specific annotation. This annotation acts as a shortcut to @Controller and @responseBody. When using this annotation, you no longer need to use the @responseBody annotation on the method. Here is sample code that uses this annotation:

In the 1-1-16 s, @ ModelAttribute

With this annotation, you can access the model that already exists in the controller by the model index name. Here is a simple example of using this annotation:
As with the @pathVariable and @RequestParam annotations, you do not need to specify an index name if the parameter name has the same name as the model, as in the following shorthand:
In particular, if you annotate a method with @ModelAttribute, Spring binds the return value of the method to a specific Model. The following is an example:
All methods annotated by the @ModelAttribute annotation will be executed before Spring invokes the specific processing method. (Hope to learn springboot more systematically, you can reply “Springboot aggregation” in Java bosom friend public account, get SpringBoot tutorial)

In the 1-1-17 s, @ CrossOrigin

The @Crossorigin annotation provides cross-domain invocation support for request handling classes or request handling methods. If we annotate the class with this annotation, all methods in the class gain cross-domain support. The advantage of using this annotation is that you can fine-tune cross-domain behavior. An example of using this annotation is as follows:

In the 1-1-18 s, @ InitBinder

The @initBinder annotation is used to annotate methods that initialize WebDataBinider for processing form data passed through Http requests, such as time formatting, string manipulation, and so on. Here is an example of using this annotation:

1-2, Spring Bean annotations

In this section, I focus on four annotations related to Spring Beans and how they are used.

In the 1-2-1 s, @ ComponentScan

The @ComponentScan annotation is used to configure the package that Spring needs to scan for classes annotated by component annotations. You can configure the basePackages property or value property to specify the packet path to scan. The value property is an alias for basePackages. The usage of this note is as follows:

In the 1-2-2 s, @ Component

The @Component annotation is used to annotate a common Component class. It has no clear business scope and simply informs Spring that the annotated class needs to be incorporated into the Spring Bean container and managed. An example of the use of this annotation is as follows:

In the 1-2-3 s, @ Service

The @service annotation is an extension (special case) of @Component that is used to annotate business logic classes. As with the @Component annotation, classes annotated by this annotation are automatically managed by Spring. Here is an example using the @service annotation:

In the 1-2-4 s, @ the Repository

The @Repository annotation is an extension of the @Component annotation. Like the @Component annotation, classes annotated by this annotation are automatically managed by Spring. The @Repository annotation is used to annotate data persistence classes in the DAO layer. The usage of this note is as follows:

2, Spring Dependency Inject and Bean Scops annotation

2-1. Spring DI annotations

In the 2-1-1 s, @ DependsOn

The @dependson annotation can configure the Spring IoC container to initialize other Bean objects before initializing one Bean. Here is sample code for using this annotation:

In the 2-1-2 s, @ Bean

The main purpose of the @bean annotation is to tell Spring that the classes annotated by this annotation will need to be included in the Bean management factory. The @bean annotation is very simple to use. In this article, I will emphasize the use of initMethod and destroyMethod in the @bean annotation. The following is an example:

2-2. Scops Notes

In the 2-2-1 s, @ the Scope

The @scope annotation can be used to define the Scope of the classes tagged with the @Component annotation and the Scope of the classes tagged with the @Bean. The Scope of @scope is: Singleton, Prototype, Request, Session, globalSession, or any custom Scope. (Hope to learn springboot more systematically, you can reply “Springboot aggregation” in Java bosom friend public account, get SpringBoot tutorial)
Prototype is used as an example. When a Spring Bean is declared prototype, the Spring IoC container initializes a new instance of the modified class each time the class needs to be used. When defining a Bean, you can set the scope property of the Bean to prototype: scope= “prototype” or use the @scope annotation as follows:
@Scope(value=ConfigurableBeanFactory.SCOPE_PROPTOTYPE)Copy the code
Here are two different ways to use the @Scope annotation, with sample code:

2-2-2, @Scope singleton mode

When the Scope of @Scope is set to Singleton, the class marked by this annotation is initialized only once by the Spring IoC container. By default, the Spring IoC container initializes class instances as Singletons. In the same way, there are two configurations for this situation, with the following example code:

3. Container configuration annotations

3-1, the @autowired

The @AutoWired annotation is used to mark dependencies that Spring will resolve and inject. This annotation can be applied to constructors, fields, and setter methods.

3-1-1, applied to the constructor

Here is an example of the @Autowired annotation annotation constructor in use:

3-1-2, acting on the setter method

Here is sample code for the @AutoWired annotation to annotate setter methods:

3-1-3, acting on fields

Annotating a field is the simplest, just add this annotation to the corresponding field. Example code is as follows:

3-2, @ Primary

When multiple beans of the same type need to be configured in the system, @primary can define the priority of these beans. Here is an example code to illustrate this feature:
Output result:
this is send DingDing method message.Copy the code

3-3 @postconstruct and @predestroy

It’s worth noting that these two annotations are not part of Spring; they are derived from two annotations in JSR-250, located in common-Annotations. Jar. The @postconstruct annotation is used to annotate methods that need to be executed before the Bean is initialized by Spring. The @predestroy annotation is used to annotate the methods that need to be executed before the Bean is destroyed. Here is the concrete example code:

3-4, @ the Qualifier

When there are multiple beans of the same type in the system, @AutoWired does not know which implementation class to choose for dependency injection. At this point, we can use the @Qualifier annotation to fine-tune to help @AutoWired select the right dependency. Here is an example of code for this annotation:

4. Spring Boot annotations

4-1, @ SpringBootApplication

The @SpringBootApplication annotation is a quick configuration annotation that defines one or more beans in the class it annotates and automatically triggers automatic configuration of beans and automatic scanning of components. This annotation is equivalent to @Configuration, @EnableAutoConfiguration, and @ComponentScan. This annotation is used in the main class of the Spring Boot application. Example code is as follows:
@SpringBootApplicationpublic class Application{    public static void main(String [] args){        SpringApplication.run(Application.class,args);    }}Copy the code

4-2, @ EnableAutoConfiguration

The @enableAutoConfiguration annotation is used to inform Spring to automatically configure configuration items associated with dependencies imported under the current classpath.

4-3, @ ConditionalOnClass and @ ConditionalOnMissingClass

These two annotations are class-conditional annotations that determine whether certain configurations should be performed based on the presence or absence of a class. Here is a simple example code:
@Configuration@ConditionalOnClass(DataSource.class)class MySQLAutoConfiguration { //... }Copy the code

4-4. @conditionalonBean and @conditionalonmissingBean

These two annotations are object conditional annotations that determine whether certain configuration methods should be performed based on the presence or absence of an object. Example code is as follows:
@Bean@ConditionalOnBean(name="dataSource")LocalContainerEntityManagerFactoryBean entityManagerFactory() {/ /... }@Bean@ConditionalOnMissingBeanpublic MyBeanmyBean() {/ /... }Copy the code

4-5, @ ConditionalOnProperty

The @conditionalonProperty annotation decides whether to execute the labeled method based on whether the configuration items in the Spring configuration file meet the configuration requirements. Example code is as follows:
@Bean@ConditionalOnProperty(name="alipay",havingValue="on")Alipay alipay() {returnnew Alipay(); }Copy the code

4-6, @ ConditionalOnResource

The following is an example of code that uses this annotation to detect methods that trigger when a configuration file is enabled:
@ConditionalOnResource(resources = "classpath:website.properties")Properties addWebsiteProperties() {/ /... }Copy the code

4 to 7, with @ @ ConditionalOnWebApplication ConditionalOnNotWebApplication

These two 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 its session. Here is a simple example:
@ConditionalOnWebApplicationHealthCheckController healthCheckController() {/ /... }Copy the code

4 to 8, @ ConditionalExpression

This annotation allows us to control more fine-grained constraints on express-based configuration conditions. When an expression satisfies a condition or when the expression is true, the method marked by this annotation is executed.
@Bean@ConditionalException("${localstore} && ${local == 'true'}")LocalFileStore store() {/ /... }Copy the code

4-9, @ Conditional

The @Conditional annotation can control more complex configuration conditions. If Spring’s built-in condition control annotations do not meet application requirements, you can use this annotation to define your own control conditions to meet your own requirements. Here is a simple example of using this annotation:
@Conditioanl(CustomConditioanl.class)CustomProperties addCustomProperties() {/ /... }Copy the code

conclusion

This summary of Spring Boot common types of annotations in the use of the way, so that we can unified Spring Boot commonly used annotations have a comprehensive understanding. For reasons of space, some notes about Spring Boot that are not commonly used will be added and explained in the next share.


, END,

The growth path of programmers

Though the road is long, the journey is sure to come

This article was originally posted on the wechat public account of the same name “The Growth of programmers”, reply to “1024” you know, give a thumbs up.

Reply [520] to receive the best learning method for programmers

Reply to [256] for Java programmer growth plans