1. @SpringBootApplication

We can think of @SpringBootApplication as a collection of @Configuration, @EnableAutoConfiguration, and @ComponentScan annotations.

  • @EnableAutoConfiguration: Enables SpringBoot automatic configuration
  • @ComponentScan: scan be@Component (@Service.@ControllerAnnotated beans, which by default scan all classes in the package that class is in.
  • @Configuration: Allows registering additional beans or importing additional configuration classes in the Spring context

2. Spring Bean correlation

2.1. @Autowired

Automatically import objects into classes. The injected classes are also managed by the Spring container. For example, the Service class is injected into the Controller class.

2.2. Component.@Repository.@Service.@Controller

We typically use the @Autowired annotation to have the Spring container automatically assemble our beans for us. To identify a class as a bean that can be used with the @AutoWired annotation auto-assembly, use the following annotation:

  • @Component: generic annotation that can mark any class asSpringComponents. This can be used if a Bean does not know which layer it belongs to@ComponentAnnotation annotation.
  • @Repository: Corresponds to the Dao layer, which is mainly used for database operations.
  • @Service: Corresponds to the service layer, which mainly involves some complex logic and requires the Dao layer.
  • @Controller: Corresponding to the Spring MVC control layer, the primary user accepts the user request and calls the Service layer to return data to the front-end page.

Note: the above function is the same, but the annotation is meaningful.

2.3. @RestController

The @RestController annotation is a combination of @Controller and @responseBody, indicating that this is a Controller bean and that the return value of the function is inserted directly into the body of the HTTP response, which is a REST-style Controller.

2.4. @Scope

There are four common Spring Bean scopes:

  • Singleton: A unique bean instance. Beans in Spring are singleton by default. (the default)
  • Prototype: Each request creates a new bean instance.
  • Request: Each HTTP request generates a new bean that is valid only within the current HTTP Request.
  • Session: Each HTTP request generates a new bean that is valid only for the current HTTP session.

2.5. @Configuration

You can use the @Component annotation instead, but using the Configuration annotation to declare Configuration classes is more semantic.

3. Handle common HTTP request types

@GetMapping("/users")
@RequestMapping(value="/users",method=RequestMethod.GET)
Copy the code
  • GET: Requests a specific resource from the server. Here’s an example:GET /users(Get all students)
  • POST: Creates a new resource on the server. Here’s an example:POST /users(Create student)
  • PUT: Updates the resource on the server (the client provides the updated entire resource). Here’s an example:PUT /users/12(Update student no. 12)
  • DELETE: Deletes a specific resource from the server. Here’s an example:DELETE /users/12(Delete student no. 12)
  • PATCH: Updates resources on the server (the client provides the changed properties, which can be regarded as partial updates)

4. Send values to the front and back ends

4.1. @PathVariable@RequestParam

@pathVariable is used to get path parameters, and @requestParam is used to get query parameters.

4.2. @RequestBody

It is used to read the body of a Request (POST,PUT,DELETE,GET) and its content-type is in application/ JSON format. After receiving the data, it will automatically bind the data to a Java object. The system uses HttpMessageConverter or a custom HttpMessageConverter to convert the JSON string in the body of the request into a Java object.

A request method can have only one @requestBody, but can have multiple @RequestParam and @PathVariable.

5. Read the configuration information

5.1. @value

Use @value (“${property}”) to read simpler configuration information:

5.2. @ConfigurationProperties

The configuration information is read and bound to the bean via @ConfigurationProperties.

5.3. PropertySource

PropertySource Reads the specified properties file

Note: Read the priority of the configuration file

6. Verify parameters

6.1. Some common annotations for field validation

  • @NotEmptyThe annotated string cannot be null or null
  • @NotBlankThe annotated string is non-null and must contain a non-whitespace character
  • @NullThe annotated element must be NULL
  • @NotNullThe annotated element must not be NULL
  • @AssertTrueThe annotated element must be true
  • @AssertFalseThe annotated element must be false
  • @Pattern(regex=,flag=)The annotated element must conform to the specified regular expression
  • @EmailThe annotated element must be in Email format.
  • @Min(value)The annotated element must be a number whose value must be greater than or equal to the specified minimum
  • @Max(value)The annotated element must be a number whose value must be less than or equal to the specified maximum
  • @DecimalMin(value)The annotated element must be a number whose value must be greater than or equal to the specified minimum
  • @DecimalMax(value)The annotated element must be a number whose value must be less than or equal to the specified maximum
  • @Size(max=, min=)The size of the annotated element must be within the specified range
  • @Digits (integer, fraction)The annotated element must be a number and its value must be within an acceptable range
  • @PastThe annotated element must be a past date
  • @FutureThe annotated element must be a future date

6.2. Validating the RequestBody

We need to verify the parameters with the @ Valid annotations, if it fails, it throws MethodArgumentNotValidException

6.3. Validate the Request Parameters (Path Variables and Request Parameters)

Make sure, make sure you don’t forget to add to the class@ValidatedAnnotated, this parameter tells Spring to validate method arguments.

7. Handle the Controller layer exception globally

Related notes:

  1. @ControllerAdviceAnnotation defines the global exception handling class
  2. @ExceptionHandler: annotation declares exception handling methods

8. JPA

8.1. Create the tables

Entity declares that a class corresponds to a database Entity.

@table Sets the Table name

8.2. Create a primary key

@id: Declare a primary key for a field.

After using the @ID declaration, we also need to define a primary key generation strategy. We can specify a primary key generation strategy using @GeneratedValue.

 The persistence engine generates the primary key from a specific table in the relational database, */
    TABLE,

    /** * In some databases, self-growth of primary keys is not supported. For example, Oracle and PostgreSQL provide a mechanism called sequence to generate primary keys */
    SEQUENCE,

    /** * The primary key grows */
    IDENTITY,

    /** * Passes the primary key generation strategy to the persistence engine, which will choose one of the three primary key generation strategies */ based on the databaseAUTO (default)Copy the code

8.3. Set the field type

@column declares the field.

8.4. Specify not to persist a specific field

@TRANSIENT: declare a field that does not need to be mapped to the database and does not need to be saved to the database when saved.

8.5. Declare large fields

@lob: Declares a field as a large field.

8.6. Create fields of enumeration type

You can use fields of Enumerated type, but the Enumerated fields are decorated with the @Enumerated annotation.

8.7. Delete/Modify data

The @Transactional annotation indicates to JPA that this operation is a modification operation. Note that this operation is also used with the @Transactional annotation.

8.8. Association

  • @OneToOneDeclare a one-to-one relationship
  • @OneToManyDeclare a one-to-many relationship
  • @ManyToOneDeclare many-to-one relationships
  • MangToMangDeclare many-to-many relationships

9. The transaction@Transactional

Use the @Transactional annotation on the method you want to start the transaction!

Tips: Transaction failures:

@Transactional applies to methods that are not public decorates

The @transactional attribute Propagation is incorrectly set. The transaction will not be rolled back if the following propagation is incorrectly set.

TransactionDefinition.PROPAGATION_SUPPORTS

TransactionDefinition.PROPAGATION_NOT_SUPPORTED

TransactionDefinition.PROPAGATION_NEVER

Error setting @transactional annotation rollbackFor

By default, Spring does not check for unchecked exceptions (exceptions inherited from RuntimeException) or Error to roll back a transaction

A method call from the same class causes @transactional to fail

For example, there is A class Test whose method A calls method B of the class (whether public or private), but method A does not declare an annotation transaction, while method B does. Method B’s transaction will not take effect after an external call to method A.

The Transactional exception is “eaten” by your catch causing @Transactional to fail

6. Database engine does not support transactions (MyISAM)

10. Json data processing

10.1. Filtering JSON Data

@JsonIgnorePropertiesUsed on a class to filter out specific fields without returning or parsing.

@JsonIgnoreCommonly used on class properties, and above@JsonIgnorePropertiesThe same.

10.2. Formatting JSON Data

JsonFormat is used to format JSON data.

10.3. Flatten objects

Using the @ JsonUnwrapped

11. Test relevance

@ActiveProfilesTypically used on test classes to declare valid Spring configuration files.

@TestDeclare a method as a test method

@TransactionalData for declared test methods is rolled back to avoid contaminating test data.

@WithMockUserProvided by Spring Security to simulate a real user and grant permissions.