Detailed Explanation of SpringBoot and Integrated Component Annotations (1) - lomback && JPA

1. Commonly used annotations

1、@SpringbootApplication

Is a composite annotation, including @ ComponentScan, and @ SpringBootConfiguration, @ EnableAutoConfiguration.

  • @SpringBootConfigurationInherited from @Configuration, the functions of the two are also the same. The current class is marked as a configuration class, and one or more @Beaninstances of the methods marked with annotations declared in the current class will be included in srpingthe container, and the instance name is the method name.
  • @EnableAutoConfigurationThe function is to start automatic configuration, which means to Springbootconfigure the default configuration of your project according to the jar package you added, for example, spring-boot-starter-web to judge whether your project needs to be added webmvcor not tomcat, and it will automatically help you configure the default configuration required in the web project.
  • @ComponentScan@Component, scan the classes marked with , @Controller, @Service, @Repositoryannotations under the current package and its subpackages and bring them into the spring container for management. is previous <context:component-scan>(previously used tags used in xml, used to scan parallel support for package configuration).

 

2、@Configuration 

Starting from Spring 3.0, @Configuration is used to define the configuration class, which can replace the xml configuration file. The annotated class contains one or more methods annotated by @Bean. These methods will be scanned by the AnnotationConfigApplicationContext or AnnotationConfigWebApplicationContext class and used to build the bean definition and initialize the Spring container.

Configuration class notes:

 

 3、@RestController

It is a collection of @Controller and @ResponseBody, indicating that this is a controller bean, and the return value of the function is directly filled in the HTTP response body, which is a REST-style controller. 

4. @Autowired and @Resource

1) Both @Autowired and @Resource can be used to assemble beans. Both can be written on the field or on the setter method.

2) @Autowired is assembled by type by default (this annotation belongs to spring). By default, dependent objects must be required to exist. If you want to allow null values, you can set its required attribute to false, such as: @Autowired(required=false), if we want to use name assembly, we can use it in conjunction with @Qualifier annotation

3) @Resource (this annotation belongs to J2EE), the default is to assemble according to the name, and the name can be specified through the name attribute. If the name attribute is not specified, when the annotation is 
written on the field, the default field name is used to search according to the name. If the annotation is written on the setter method, the default attribute name is used for assembly. Wiring is done by type when no bean matching the name is found. But it should be noted that if the name attribute is specified, it will only be assembled according to the name.

5、@PathVariable

The URL with placeholders is a new feature of Spring 3.0. This feature is a milestone in the development of SpringMVC towards the REST goal. Through @PathVariable, the placeholder parameters in the URL can be bound to the input parameters of the controller processing method: {xxx} placeholders in the URL can be bound to the input parameters of the operation method through @PathVariable("xxx").

6、@JsonBackReference、@JsonManagedReference和@JsonIgnore

1) The two annotations @JsonBackReference and @JsonManagedReference are usually used in pairs, usually in parent-child relationships. The attribute marked by @JsonBackReference will be ignored during serialization (serialization, that is, converting the object into json data) (that is, the json data in the result does not contain the content of the attribute).

2) The properties marked with @JsonManagedReference will be serialized. When serializing, @JsonBackReference is equivalent to @JsonIgnore, and @JsonManagedReference can be omitted at this time. But in deserialization (deserialization, that is, json data is converted into an object), if there is no @JsonManagedReference, the properties marked by @JsonBackReference (ignored parent or child) will not be automatically injected; if there is @JsonManagedReference, the properties marked by @JsonBackReference will be automatically injected.  

3) @JsonIgnore directly ignores a property to break infinite recursion, and both serialization and deserialization are ignored. Of course, if marked in the get and set methods, they can be controlled separately. The serialization corresponds to the get method, and the deserialization corresponds to the set method. In a parent-child relationship, when deserialized, @JsonIgnore will not automatically inject ignored property values ​​(parent or child), which is the biggest difference between it and @JsonBackReference and @JsonManagedReference.  

7、@RequestMapping

Provides routing information and is responsible for mapping URLs to specific functions in the Controller.

8、@Import

In the application, sometimes a class is not injected into the IOC container, but the bean corresponding to the class needs to be obtained when it is used. At this time, the @Import annotation needs to be used.

9、ImportResource

ImportResource is used to load xml configuration files.

10、@Service、@Component、@Repository、@Controller

  1. @Configuration configuration class cannot be final type;
  2. @Configuration configuration classes cannot be anonymous classes;
  3. Nested configuration classes must be static classes.

@Service is used to mark business layer components,

@Controller is used to mark the control layer components,

@Repository is used to mark data access components, namely DAO components,

@Component refers to components in general. When components are not easy to classify, we can use this annotation to mark them.

11、@Bean

A method marked with @Bean is equivalent to a bean configured in XML.

12、@Value

Inject the property with the value of the property configured by Spring boot application.properties.

13、@Inject

Equivalent to the default @Autowired, but without the required attribute.

14、@RequestBody

1) It is often used to deal with content-types other than the default application/x-www-form-urlcoded encoded content, for example: application/json or application/xml, etc. Generally speaking, it is commonly used to deal with application/json types.

2) Through @requestBody, the JSON string in the request body can be bound to the corresponding bean, of course, it can also be bound to the corresponding string respectively.

3) In some special cases, @requestBody can also be used to process content whose content-type type is application/x-www-form-urlcoded, but this method is not very common. When processing such requests, @requestBody will put the processing results into a MultiValueMap<String, String>, which is generally used in special cases. For example, jQuery easyUI's datagrid needs to use this method when requesting data, and small projects only create a POJO class. You can also use this accept method

15、@RequestParam

It is used to assign the specified request parameter to the formal parameter in the method.

16、@ModelAttribute

Bind parameters to the Model object

17、@Primary

When there are multiple bean candidates during automatic assembly, the bean annotated as @Primary will be the preferred one, otherwise an exception will be thrown.

18、@Qualifier

Qualifier means qualified person. Through this mark, it indicates which implementation class is what we need. Add @Qualifier annotation. It should be noted that the parameter name of @Qualifier is one of the names we defined @Service annotation before.

19、@PostConstruct、@PreConstruct

1)@PostConstruct

     The method modified by @PostConstruct will run when the server loads the Servlet, and will only be called once by the server, similar to the inti() method of Serclet. The method modified by @PostConstruct will run after the constructor and before the init() method.

2)@PreConstruct

     The method modified by @PreConstruct will run when the server unloads the Servlet, and will only be called once by the server, similar to the destroy() method of the Servlet. The method modified by @PreConstruct will run after the destroy() method, before the Servlet is completely unloaded.

Two, lomback annotation

1、@Getter

The entity class generates the corresponding get() method

2、@Setter

The entity class generates the corresponding set() method

3、@Data

1) This annotation is used on the class, which is the most commonly used annotation, which combines @ToString, @EqualsAndHashCode, @Getter and @Setter. Essentially using @Dataannotations, class default sums @ToStringand @EqualsAndHashCodeeach field has @Settersums @getter. This annotation also generates a public constructor that can take any @NonNulland finalfields as parameters.

2) While @Datathe annotation is very useful, it does not have the same granularity of control as other annotations. @DataProvide a single parameter that can generate a static factory, set staticConstructorthe parameter to the required name, set the constructor automatically generated by Lombok as private, and provide a public static factory method with the given name.

4、@NonNull

This annotation is used on the attribute, which is used for the non-null check of the attribute. When placed on the field of the setter method, a null check will be generated, and if it is empty, it will be thrown NullPointerException. This annotation will generate a parameterless constructor by default. 

5、@ToString

This annotation is used on the class, which by default generates any non-podium field output in the form of name-value. 
1) If necessary, you can includeFieldNamescontrol whether the attribute name is included in the output through the annotation parameter. 
2) excludeSpecific fields can be excluded from the generated method by including field names in the parameters. 
3) You can callSupercontrol the output of the parent class through parameters.
 

6、@EqualsAndHashCode

This annotation is used on the class , and the annotation at the class level will generate equals()and at the same time hashCode(). If there is an inheritance relationship, callSuperthe parameter needs to be set to true.

7、@AllArgsConstructor

This annotation is used on the class , which provides a full-parameter construction method, and does not provide no-argument construction by default. 

8、@NoArgsConstructor

This annotation is used on the class , which provides a no-arg construction.

9、@RequiredArgsConstructor

This annotation is used on the class to generate corresponding constructors for all member variables annotated with @NonNull or with final modification in the class. 

10、@Value

This annotation acts on the entity class, and will generate a constructor with all parameters, the get () method, and also provides equals (), hashCode (), and toString () methods. 
Note: no setter  ()

11、@Cleanup

This annotation is used before the property, and this annotation is used to ensure that the allocated resources are released. Using this annotation on a local variable, any subsequent code will be encapsulated in try/finally to ensure that the resources currently in effect are released. The default @Cleanupcleaning method is that closeyou can use value to specify different method names.

3. JPA annotations 

1、@Entity

@Entity is used for entity classes, indicating that the Java class is an entity class and will be mapped to the specified database table. If you declare an entity class User, it will be mapped to the user table in the database.

2、@Table

1) When the name of the entity class and its mapped database table name are different, you need to use the @Table annotation description. This annotation is used in parallel with the @Entity annotation and placed before the entity class declaration statement. It can be written in a separate statement line or with the declaration statement.

2) The common option of @Table annotation is name, which is used to specify the table name of the database. @Table annotation also has two options, catalog and schema, which are used to set the database catalog or schema to which the table belongs, usually the database name.

3、@Id

The @Id annotation is used to declare that an attribute of an entity class is mapped to the primary key column of the database. The attribute is usually placed before the attribute declaration statement, and it can go with the declaration statement or be written on a separate line. The @Id annotation can also be placed before the property's getter() method.

4、@GeneratedValue

@GeneratedValue is used to mark the generation strategy of the primary key, specified by the strategy attribute. By default, JPA automatically selects a primary key generation strategy that is most suitable for the underlying database: SqlServer corresponds to identity, and MySQL corresponds to auto increment. The following alternative strategies are defined in javax.persistence.GenerationType:

IDENTITY: The primary key field is self-incremented by using the database ID self-increment method, which is not supported by Oracle;

AUTO: JPA automatically selects the appropriate strategy, which is the default option;

SEQUENCE: Generate the primary key through the sequence,  specify the sequence name through  the @SequenceGenerator annotation, MySql does not support this method

TABLE: The primary key is generated through the table. The framework generates the primary key through the table simulation sequence. Using this strategy can make the application easier to migrate to the database.

5、@Basic

@Basic represents a simple mapping of attributes to database table fields, which exists by default.

@Basic fetch: Indicates the reading strategy of this attribute. There are two types: EAGER and LAZY, which represent main branch fetching and lazy loading respectively. The default is EAGER.

optional: Indicates whether the attribute is allowed to be null, the default is true

6、@Column

When the attribute of the entity has a different name from the column of the database table to which it is mapped, the @Column annotation needs to be used. This attribute is usually placed before the attribute declaration statement of the entity, and can also be used together with the @Id annotation.

The common attribute of @Column annotation is name, which is used to set the column name of the mapping database table. In addition, the label also contains other attributes, such as : unique, nullable, length, etc.

The columnDefinition attribute of @Column annotation: Indicates the actual type of the field in the database. Usually the ORM framework can automatically determine the type of the field in the database according to the attribute type, but it is still impossible to determine whether the field type in the database is DATE, TIME or TIMESTAMP for the Date type. In addition, the default mapping type of String is VARCHAR. If you want to map the String type to the BLOB or TEXT field type of a specific database.

The @Column annotation can also be placed before the getter method of the property

7、@Transient

Indicates that the attribute is not a mapping to a field of a database table, and the ORM framework will ignore this attribute. If an attribute is not a field mapping of a database table, it must be marked as @Transient, otherwise, the ORM framework defaults to its annotation as @Basic

8、@Temporal

The temporal precision of the Date type is not defined in the core Java API. In the database, data representing the Date type has three precisions: DATE, TIME, and TIMESTAMP (that is, simple date, time, or both), and the @Temporal annotation can be used to adjust the precision when performing attribute mapping.

9、@TableGenerator

The value of the current primary key is saved separately in a database table, and the value of the primary key is obtained by querying the specified table every time. This method of generating a primary key can be applied to any database, and there is no need to worry about problems caused by incompatibility of different databases.

Attributes:

1) The name attribute indicates the name of the primary key generation strategy, which is referenced in the generator value set in @GeneratedValue

2) The table attribute indicates the name of the table persisted by the table generation strategy

3) The value of the pkColumnName attribute represents the name of the key value corresponding to the primary key generation strategy in the persistent table

4) The value of the valueColumnName attribute represents the value currently generated by the primary key in the persistent table, and its value will be accumulated with each creation

5) The value of the pkColumnValue attribute represents the primary key corresponding to the generation strategy in the persistent table

6) allocationSize indicates the size of each primary key value increase, the default value is 50

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_42133100/article/details/89084518