SpringBoot annotations and springboot annotations

Source: Internet
Author: User

SpringBoot annotations and springboot annotations

I. annotations list

@ SpringBootApplication: Contains @ ComponentScan, @ Configuration, and @ EnableAutoConfiguration annotations. @ ComponentScan enables spring Boot to scan the Configuration class and add it to the program context.

@ Configuration is equivalent to the XML Configuration file of spring. Java code can be used to check type security.

@ EnableAutoConfiguration automatic configuration.

@ ComponentScan component scan: automatically discovers and assembles beans.

@ Component can be used with CommandLineRunner to execute some basic tasks after the program starts.

The @ RestController annotation is a collection of @ Controller and @ ResponseBody, indicating that this is a Controller bean and directly fills in the return value of the function in the HTTP response body. It is a REST-style Controller.

@ Autowired Automatic Import.

@ PathVariable get parameters.

@ JsonBackReference solves the problem of nested external links.

@ RepositoryRestResourcepublic works with spring-boot-starter-data-rest.

2. annotations

@ SpringBootApplication: declare that spring boot will automatically configure the program. This Configuration is equivalent to three configurations: @ Configuration, @ EnableAutoConfiguration and @ ComponentScan.

  1 package com.example.myproject;  2 import org.springframework.boot.SpringApplication;  3 import org.springframework.boot.autoconfigure.SpringBootApplication;  4   5 @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan   6 public class Application {  7    public static void main(String[] args) {  8      SpringApplication.run(Application.class, args);  9    } 10 }

@ ResponseBody: indicates that the returned results of this method are directly written to the HTTP response body. It is generally used for Asynchronously obtaining data and is used to build a RESTful api. After @ RequestMapping is used, the returned values are usually parsed as jump paths. After @ esponsebody is added, the returned results are not parsed as jump paths, but directly written into the HTTP response body. For example, json data is obtained asynchronously. After @ Responsebody is added, json data is directly returned. This annotation is generally used together with @ RequestMapping. Sample Code:

  1 @RequestMapping(“/test”)  2 @ResponseBody  3 public String test(){  4    return”ok”;  5 }

@ Controller: defines the Controller class. In the spring Project, the Controller is responsible for forwarding URL requests sent by users to the corresponding service interface (service layer). Generally, this annotation is in the class, the method usually needs to be annotated with @ RequestMapping. Sample Code:

1 @ Controller 2 @ RequestMapping ("/demoInfo") 3 public class DemoController {4 @ Autowired 5 private DemoInfoService demoInfoService; 6 7 @ RequestMapping ("/hello ") 8 public String hello (Map <String, Object> map) {9 System. out. println ("DemoController. hello () "); 10 map. put ("hello", "from TemplateController. helloHtml "); 11 // use hello.html or hello. the ftl template is used for rendering and display. 12 return "/hello"; 13} 14}

@ RestController: a collection of control layer components (such as actions in struts), @ ResponseBody, and @ Controller. Sample Code:

  1 package com.kfit.demo.web;  2   3 import org.springframework.web.bind.annotation.RequestMapping;  4 import org.springframework.web.bind.annotation.RestController;  5   6   7 @RestController  8 @RequestMapping(“/demoInfo2”)  9 publicclass DemoController2 { 10  11 @RequestMapping("/test") 12 public String test(){ 13    return "ok"; 14 } 15 }

@ RequestMapping: Provides route information and maps URLs to specific functions in the Controller.

@ EnableAutoConfiguration: SpringBoot auto-configuration: automatically configure your Spring application based on the jar dependency you added. For example, if your classpath has HSQLDB and you have not manually configured any database connection beans, We will automatically configure an in-memory database ". You can add the @ EnableAutoConfiguration or @ SpringBootApplication annotation to a @ Configuration class and select automatic Configuration. If you find that you have applied a specific automatic configuration class that you do not want, you can use the exclusion attribute of the @ EnableAutoConfiguration annotation to disable them.

@ ComponentScan: indicates the automatic discovery and scanning component of this class. In my personal understanding, if a class with annotation such as @ Component, @ Controller, and @ Service is scanned and registered as Bean, all Spring components, including the @ Configuration class, can be automatically collected. We often use the @ ComponentScan annotation to search for beans and import them with the @ Autowired annotation. All Spring components, including the @ Configuration class, can be automatically collected. We often use the @ ComponentScan annotation to search for beans and import them with the @ Autowired annotation. If no configuration is available, Spring Boot will scan the classes with annotations such as @ Service and @ Repository in the package where the startup class is located and under the sub-package.

@ Configuration: equivalent to a traditional xml Configuration file. If some third-party libraries need to use xml files, we recommend that you still use the @ Configuration class as the main Configuration class of the project-you can use the @ ImportResource annotation to load the xml Configuration file.

@ Import: used to Import other configuration classes.

@ ImportResource: used to load the xml configuration file.

@ Autowired: automatically import the dependent bean

@ Service: It is generally used to modify components at the service layer.

@ Repository: The @ Repository annotation ensures that DAO or repositories provides abnormal translation. The DAO or repositories class modified by this annotation will be discovered and configured by ComponetScan, you do not need to provide XML configuration items for them.

@ Bean: The @ Bean annotation method is equivalent to the bean configured in XML.

@ Value: inject the property Value configured by Spring boot application. properties. Sample Code:

  1 @Value(value = “#{message}”)  2 private String message;

@ Inject: equivalent to the default @ Autowired, but does not have the required attribute;

@ Component: Refers to a Component. This annotation can be used to mark components that are not classified.

@ Bean: Put the bean in XML on the method instead of the class, which means to generate a Bean and hand it over to spring for management.

@ AutoWired: automatically imports the dependent bean. ByType method. Use the configured Bean to assemble attributes and methods. It can mark class member variables, methods, and constructors to complete automatic assembly. When (required = false) is added, no error is returned even if the bean cannot be found.

@ Qualifier: You can use @ Qualifier ("name") to specify multiple beans of the same type. Works with @ Autowired. @ Qualifier: In addition to injecting a descriptor by name, the descriptor can be more fine-grained to control how to select candidates. The specific usage is as follows:

  1 @Autowired  2 @Qualifier(value = “demoInfoService”)  3 private DemoInfoService demoInfoService;

@ Resource (name = "name", type = "type"): If there is no content in brackets, the default value is byName. Similar to @ Autowired.

Iii. JPA Annotation

@ Entity: @ Table (name = ""): indicates that this is an Entity class. It is generally used for the jpa annotations. However, if the Table name and object class name are the same, @ Table can be omitted.

@ MappedSuperClass: used to determine the entity of the parent class. The property subclass of the parent class can be inherited.

@ NoRepositoryBean: generally used as the repository of the parent class. With this annotation, spring will not instantiate the repository.

@ Column: if the field name is the same as the Column name, it can be omitted.

@ Id: indicates that this attribute is the primary key.

@ GeneratedValue (strategy = GenerationType. SEQUENCE, generator = "repair_seq"): indicates that the primary key generation policy is sequence (which can be Auto, IDENTITY, native, etc., and Auto indicates that it can be switched between multiple databases ), the name of the specified sequence is repair_seq.

@ SequenceGeneretor (name = "repair_seq", sequenceName = "seq_repair", allocationSize = 1): name is the name of the sequence for use. sequenceName is the database sequence name, the two names can be consistent.

@ Transient: indicates that this attribute is not a ing of fields in the database table. The ORM framework ignores this attribute. If an attribute is not a field ing of a database table, you must mark it as @ Transient. Otherwise, the orm framework annotation is @ Basic by default. @ Basic (fetch = FetchType. LAZY): indicates how object attributes can be loaded.

@ JsonIgnore: ignores some attributes of Java bean during json serialization, and affects both serialization and deserialization.

@ JoinColumn (name = "loginId"): one-to-one: the foreign key pointing to another table in this table. One-to-multiple: the other table points to the foreign key of the table.

@ OneToOne, @ OneToMany, and @ ManyToOne: corresponds to one-to-one, one-to-many, and multiple-to-one in the hibernate configuration file.

4. springMVC related annotations

@ RequestMapping: @ RequestMapping ("/path") indicates that the controller processes all ur l requests of "/path. RequestMapping is an annotation used to process request address ing and can be used for classes or methods.
Used on the class to indicate that all methods in the class that respond to requests use this address as the parent path. The annotation has six attributes:
Params: specifies that the request must contain certain parameter values for processing.
Headers: specifies that the request must contain some specified header values before the method can process the request.
Value: Specifies the actual request address. The specified address can be in URI Template mode.
Method: Specifies the Request method type, such as GET, POST, PUT, and DELETE.
Consumes: specifies the Type of Content submitted for request processing, such as application/json, text/html;
Produces: specifies the type of the returned content. It is returned only when the (Accept) type in the request header contains the specified type.

@ RequestParam: used before the parameters of the method.
@ RequestParam
String a = request. getParameter ("").

@ PathVariable: PATH variable. For example

  1 RequestMapping(“user/get/mac/{macAddress}”)  2 public String getByMacAddress(@PathVariable String macAddress){  3    //do something;   4 }

Parameters must be the same as those in braces.

5. Global Exception Handling

@ ControllerAdvice: Contains @ Component. Can be scanned. Handle exceptions in a unified manner.

@ ExceptionHandler (Exception. class): If it is used in a method, the following method is executed in case of this Exception.

Vi. Specific configuration parsing and use environment in the project@ MappedSuperclass:

1. @ MappedSuperclass annotation is used on the parent class to identify the parent class

2. @ MappedSuperclass indicates that the class cannot be mapped to the database table because it is not a complete entity class, but its attributes can be mapped to the database table used by its subclass pair.

3. The class identified by @ MappedSuperclass cannot have @ Entity or @ Table annotations.

@ Column:

1. when the attribute of an object is different from the Column name of the database table mapped to it, the @ Column annotation must be used. This attribute is usually placed before the attribute declaration statement of the object and can be used with the @ Id annotation.

2. The common attribute marked by @ Column is name, which is used to set the name of the Column mapped to the database table. This annotation also contains multiple other attributes, such as unique, nullable, length, and precision. The details are as follows:

1 name attribute: The name attribute defines the name of the field corresponding to the labeled field in the database table.
2 unique attribute: indicates whether the field is a unique identifier. The default value is false. If a field in the table needs a unique identifier, you can use this tag, you can also use @ UniqueConstraint in the @ Table Annotation
3 nullable attribute: nullable attribute indicates whether the field can be null. The default value is true.
4. insertable attribute: The insertable attribute indicates whether to INSERT the value of this field when inserting data using the "INSERT" statement.
5. updateable attribute: The updateable attribute indicates whether to UPDATE the value of this field when inserting data using the "UPDATE" statement.
6. insertable and updateable attributes: these attributes are generally used for read-only attributes, such as primary keys and Foreign keys. These fields are usually automatically generated.
7 columnDefinition attribute: The columnDefinition attribute indicates the SQL statement created for this field when a table is created. It is generally used to generate table definitions using Entity. If the table in the database has been created, this attribute is unnecessary.
8. table attribute: The table attribute defines the name of the table containing the current field.
9 length attribute: The length attribute indicates the length of a field. This attribute is valid only when the field type is varchar. The default value is 255 characters.
The 10 precision attribute and the scale attribute indicate precision together with the precision attribute. When the field type is double, precision indicates the total length of the value, and scale indicates the number of decimal places.
The details are as follows:
1. The double type will be mapped to the double type in the database, and the precision and scale attributes are invalid.
2. If the double type is specified as decimal in the columnDefinition attribute and the precision is specified, the columnDefinition prevails.
3. The BigDecimal type is mapped to the decimal type in the database. The precision and scale attributes are valid.
4. The precision and scale attributes are valid only for the BigDecimal type.

3. @ columnDefinition attribute marked by Column: indicates the actual type of the field in the database. generally, the ORM framework can automatically determine the type of fields in the database based on the attribute type, but the Date type still cannot determine whether the field type in the database is DATE, TIME or TIMESTAMP. in addition, the default ing type of String is VARCHAR. If you want to map the String type to the BLOB or TEXT field type of a specific database.

4. @ Column annotation can also be placed before the property's getter Method

@ Getter and @ Setter (Lombok)
@ Setter: Annotation on the property; provides the setting method for the property @ Getter: Annotation on the property; provides the getting method for the property
Extension:
1 @ Data: Annotation on the class; provides the getting and setting methods for all attributes of the class, and also provides the equals, canEqual, hashCode, toString method 2 3 @ Setter: annotation on the property; provides the setting method 4 5 @ Getter for the property: Annotation on the property; provides the getting Method 6 7 @ Log4j2 for the property: Annotation on the class; provide a log4j log object named log for the class, which is similar to the @ Log4j annotation 8 9 @ NoArgsConstructor: Annotation on the class; provides a construction method 10 11 @ AllArgsConstructor for the class without parameters: Annotation on the class; provides a Construction Method 12 13 @ EqualsAndHashCode for the class with full parameters: by default, the equals and hascode methods are generated using all non-transient (non-transient) and non-static (non-static) fields. To specify which attributes to use. 14 15 @ toString: generate the toString method. By default, the class name and all attributes are output. The attributes are output in sequence and separated by commas. 16 17 @ NoArgsConstructor, @ RequiredArgsConstructor and @ AllArgsConstructor 18 No parameter constructor, partial parameter constructor, full parameter constructor. When we need to overload multiple constructors, you can only manually write 19 20 @ NonNull: Annotation on the attribute. If the annotation is made, it must not be Null 21 22 @ val: Annotation on the attribute. If the annotation is made, is set to final type, you can view the source code annotation know
@ PreUpdate and @ PrePersist

@PreUpdate
1. Specify the callback method for the corresponding lifecycle event.
2. This annotation can be applied to object classes, ing methods of superclass or callback listener classes.
3. For setter, if you want to update the attributes of an object every time you update the object, you can use @ PreUpdate annotations.
4. With this annotation, you do not have to explicitly update the corresponding attributes each time you update the user entity.
5. preUpdate does not allow you to change your entity. You can only use the change set passed to the calculation of the event to modify the original field value.

@Prepersist
1. view the @ PrePersist annotation to help you automatically fill in Object Attributes before persistence.
2. It can be used to record some business-independent fields when using jpa, such as the last update time. Life cycle method annotation (delete does not have a life cycle event)
3. Called before @ PrePersist save. It can return a DBObject instead of an empty @ PostPersist and be called after saving to datastore.
4. @ PostLoad is called after Entity is mapped @ EntityListeners to specify the external lifecycle event implementation class
Object Bean lifecycle callback event
Annotation of the method: @ PrePersist @ PostPersist @ PreRemove @ PostRemove @ PreUpdate @ PostUpdate @ PostLoad.
They are labeled before a method and have no parameters. The methods under these annotations are called before and after the entity state changes, which is equivalent to the interceptor;
Pre indicates that it is triggered before the status switch, and post indicates that it is triggered after the switch.
@ PostLoad event is triggered in the following situations:
1. Execute the EntityManager. find () or getreference () method to load an object;
2. After the jpa ql query is executed;
3. After the EntityManager. refresh () method is called.
@ PrePersist and @ PostPersist events occur when an object is inserted into the database;
@ PrePersist the event occurs immediately after the EntityManager. persist () method is called. This event also occurs when the cascade storage occurs. At this time, the data is not actually inserted into the database.
@ PostPersist occurs when the data has been inserted into the database.
@ PreUpdate and @ PostUpdate events are triggered by the update object. @ PreUpdate events are triggered before the object state is synchronized to the database. At this time, the data is not actually updated to the database.
@ PostUpdate is triggered after the entity state is synchronized to the database, and synchronization occurs when the transaction is committed.
@ PreRemove and @ PostRemove are triggered by the deletion object. @ PreRemove is triggered before the object is deleted from the database, that is, the EntityManager. remove () method or cascade deletion is called.

When you execute various persistence methods, the state of the object changes accordingly, and the state changes will lead to different lifecycle events. These events can use different annotators to indicate the callback function when the event occurs.

@ Javax. persistence. PostLoad: After loading.

@ Javax. persistence. PrePersist: Before persistence.

@ Javax. persistence. PostPersist: After persistence.

@ Javax. persistence. PreUpdate: Before update.

@ Javax. persistence. PostUpdate: After update.

@ Javax. persistence. PreRemove: before deletion.

@ Javax. persistence. PostRemove: after deletion.

 

1) Database Query

@ PostLoad event is triggered in the following situations:

Run the EntityManager. find () or getreference () method to load an object.

After JPQL query is executed.

After the EntityManager. refresh () method is called.

2) database insertion

@ PrePersist and @ PostPersist events occur when the object is inserted into the database:

@ PrePersist the event occurs immediately after the persist () method is called. At this time, the data is not actually inserted into the database.

@ PostPersist occurs when the data has been inserted into the database.

3) database updates

@ PreUpdate and @ PostUpdate events are triggered by the update entity:

@ PreUpdate is triggered before the entity state is synchronized to the database. At this time, the data has not been actually updated to the database.

@ PostUpdate is triggered after the entity state is synchronized to the database, and synchronization occurs when the transaction is committed.

4) delete a database

@ PreRemove and @ PostRemove events are triggered by the deletion object:

@ PreRemove is triggered before the object is deleted from the database, that is, when the remove () method is called to delete the object, the data is not actually deleted from the database.

@ PostRemove is triggered when the object is deleted from the database. @ NoArgsConstructor & @ AllArgsConstructor (lombok)

@ NoArgsConstructor: provides a construction method without parameters.

@ AllArgsConstructor: provides a construction method for the full parameter.

@Configuration




Reference: tanwei81; Java excellent classics. Advanced Programming volume

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.