Spring Boot summary

@SpringBootApplication

@SpringBootApplicationAn annotation is a quick configuration annotation that allows one or more beans to be defined in a class that is annotated and automatically triggers automatic configuration of beans and automatic scanning of components. This note is equivalent to@Configuration,@EnableAutoConfigurationand@ComponentScanThe combination of; This annotation is usually used on the main class.

@Configuration

Is equivalent toSpringtheXMLConfiguration file; useJavaCode can check for type safety, usually on the main class;

@EnableAutoConfiguration

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

Automatic Configuration can be implemented by adding @EnableAutoConfiguration or @SpringBootApplication annotations to the @Configuration class.

@ConditionalOnClass & @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;

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

@ConditionalOnBean & @ConditionalOnMissingBean

These two annotations are object conditional annotations that determine whether certain configuration methods should be executed based on the presence or absence of an object.

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

@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.

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

@ConditionalOnResource

A method that detects the existence of a configuration file and triggers its annotation.

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

@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.

@ConditionalOnWebApplication
HealthCheckController healthCheckController(){
 //...
}
Copy the code

@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

@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 custom control conditions to meet custom requirements.

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

@ComponentScan

@ComponentScanAnnotations are 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;

@Repository

@RepositoryAnnotations are@ComponentExtension of annotations, and@ComponentLike annotations, classes annotated by this annotation are automatically managed by Spring,@RepositoryAnnotations are used to annotate the DAO layer’s data persistence classes;

@Service

@ServiceAnnotations are@ComponentIt is used to annotate business logic classes. with@ComponentLike annotations, classes annotated by this annotation are automatically managed by Spring;

@RestController

@RestControllerIntroduced in Spring 4.0, this is a specific controller annotation. This note is equivalent to@Controllerand@ResponseBodyShortcut to. When using this annotation, you do not need to use it on methods@ResponseBodyAnnotations;

@Controller

@Controlleris@ComponentAn extension of the annotation, Spring automatically scans and configures the classes annotated by the annotation. This annotation is used to annotate the Spring MVC controller;

@ModelAttribute

Models that already exist in the controller are accessed by the model index name. If the parameter name has the same name as the model, you do not need to specify the index name;

@PostingMapping("/advice")
public String getAdvice(@ModelAttrobute User user){
    adviceService.get(user.id)
}
Copy the code

@CrossOrigin

@CrossOriginAnnotations provide 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.

@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.

@InitBinder
public void initBinder(WebDataBinder dataBinder){
    StringTrimmerEditor editor = new StringTrimmerEditor(true);
    dataBinder.registerCustomEditor(String.class,editor);
}
Copy the code

@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. In other words, when you don’t know how to categorize your components, you can choose@Component

@ResponseBody

Indicates that the return result of the method is directly written to the HTTP Response body, which is generally used when obtaining data asynchronously@RequestMappingAfter, the return value is usually resolved to the jump path, plus@responsebodyThe return result will not be parsed as a jump path, but written directly into the HTTP Response body. For example, get json data asynchronously, plus@responsebodyJson data is directly returned.

@RequestBody

Used in the parameter list of the processing request method, it can bind the parameters in the request body to an object, the request body parameters are passedHttpMessageConverterPassed, matching and binding values based on the parameter names in the request body and the object’s property names. In addition, can also pass@ValidAnnotations validate parameters in the request body.

@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 use of the @bean annotation is very simple. Here, we will focus on the @bean annotationinitMethodanddestroyMethodThe use of;

@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. Through byType, it uses the configured Bean to complete the assembly of attributes and methods. It can annotate class member variables, methods and constructors to complete the work of automatic assembly. When (required=false) is added, no error is reported even if the bean is not found;

@Primary

When multiple beans of the same type need to be configured in the system, @primary can define the priority of these beans.

@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 @AutoWired to select the right dependency;

@ the Resource (name = “name”, type = “type”)

Without parentheses, byName is the default. Similar to @autowired;

@RequestMapping

Used to map Web requests to methods in request processing classes and can be used on classes or methods. For classes, the address is the parent path of all methods that respond to requests in the class;

This annotation has six attributes:

Params: Specifies that the request must contain some parameter values for this method to process.

Headers: Specifies that the request must contain some specified header value before the method can process the request.

Value: Specifies the actual address of the request, which can be the URI Template pattern

Method: Specifies the method type of the request, such as GET, POST, PUT, and DELETE

Consumes: specify the processing request of Content Type (the content-type), such as application/json, text/HTML.

Produces: Specifies the content type returned, only if the specified type is in the (Accept) type in the Request header.

@GetMapping

@requestMapping (value= “/”, method= requestmethod.get);

@PostMapping

@requestMapping (value= “/”, method= requestmethod.post);

@PutMapping

@requestMapping (value= “/”, method= requestMethod.put);

@DeleteMapping

@requestMapping (value= “/”, method= requestmethod.delete);

@PatchMapping

@PatchMappingAnnotations are used to process HTTP PATCH requests and map the request to the corresponding processing method. PatchMapping is equivalent to@RequestMapping(method=HttpMethod.PATCH)Shortcut to.

@RequestParam

@RequestParamAnnotations are used to bind the parameters of a method to the parameters passed in the Web request. use@RequestParamYou can easily access the values of HTTP request parameters.

@PathVariable

@PathVariableAnnotations bind parameters in a method to template variables in the request URI. Can be achieved by@RequestMappingAnnotation to specify the template variable of the URI, and then use@PathVariableAnnotations bind parameters in a method to template variables.

In particular,@PathVariableAnnotations allow us to alias a parameter using the value or name attribute. Here is an example of using this annotation:

@getMapping (" API /v3/{adress}") public String getByMacAddress(@pathVariable (" adress ") String adress) {//do something; }Copy the code

@Import

Used to import other configuration classes;

@ImportResource

Used to load the XML configuration file

@DependsOn

@DependsOnAnnotations can configure the Spring IoC container to initialize other Bean objects before initializing one Bean.

@Bean("firstBean")
@DependOn("value={"SecondBean","ThirdBean"}")
public FirstBean getFirstBean(){
    return new FirstBean();
}

public SecondBean getSecondBean(){
    return new SecondBean();
}

public ThirdBean getThirdBean(){
    return new ThirdBean();
}
Copy the code

@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 limited by @scope includes:singleton,prototype,request,session,globalSessionOr any other custom scope. 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 toPrototype: scope = "prototype", can also be set using the @scope annotation;

Java @ Scope (value = ConfigurableBeanFactory. SCOPE_PROPTOTYPE) ¨ G11G Java @ Configuration @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) public class MyConfiguration{ ... }

View jar package internal structure command

Jar TVF target/myproject - 0.0.1 - the SNAPSHOT. The jar

Global exception handling

@ControllerAdvice

@ControllerAdviceIs an extension of the @Component annotation, and Spring automatically scans and detects classes flagged by @ControllerAdvice.@ControllerAdviceThe needs and@ExceptionHandler,@InitBinderAs well as@ModelAttributeAnnotations are used in conjunction with the exception information thrown by the controller.

First, we need to define a by@ControllerAdviceClass, in which a method to handle a specific exception is defined and marked with the @ExceptionHandler annotation.

In addition, it can be used when necessary@InitBinderYou configure the class globally, and you can use @ModelAttribute to configure view-specific parameters. use@ControllerAdviceAnnotations, you can quickly create unified, custom exception handling classes.

@ExceptionHandler(Exception.class)

@ExceptionHanderAnnotations are 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 controller@ExceptionHandlerMethod of labeling.

@ResponseStatus

@ResponseStatusAnnotations can mark 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

SpringCloud

@EnableEurekaServer

Used on the SpringBoot startup class to indicate that this is a Eureka service registry;

@EnableDiscoveryClient

Used on the SpringBoot startup class to indicate that it is a service that can be found by the registry;

@LoadBalanced

Enable the load balancing capability.

@EnableCircuitBreaker

Used in the start class, open the circuit breaker function;

@ HystrixCommand (backMethod fallbackMethod = “”)

In terms of methods, fallbackMethod specifies the circuit break callback method.

@EnableConfigServer

To start a class, this is a configuration center, Config Server enabled;

@EnableZuulProxy

Enable zuul routing, used in startup classes;

@SpringCloudApplication:

**@SpringBootApplication**.@EnableDiscovertyClient.@EnableCircuitBreaker

These are SpringBoot annotations, Registry Service Center Eureka annotations, and circuit breaker annotations. For SpringCloud, these are the three annotations that every microservice must have, hence the @SpringCloudApplication annotation collection.