Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Introduction of SpringBoot annotations and their uses

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail about the introduction of SpringBoot notes and its use, the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

1. Annotations list

1. @ SpringBootApplication

Includes @ ComponentScan, @ Configuration, and @ EnableAutoConfiguration annotations.

Where @ ComponentScan lets Spring Boot scan into the Configuration class and add it to the program context.

2. @ ComponentScan

Component scanning, you can automatically discover and assemble some Bean.

3. @ Configuration

XML configuration file equivalent to Spring; type safety can be checked using Java code.

4. @ EnableAutoConfiguration

Automatic configuration

5. @ RestController

This annotation is a collection of @ Controller and @ ResponseBody, indicating that this is a controller Bean and fills the return value of the function directly into the HTTP response body, which is a REST-style controller.

6. @ Autowired

Automatic import.

7, @ PathVariable

Get the parameters.

8. @ JsonBackReference

Solve the problem of nested outer chain.

9, @ RepositoryRestResourcepublic

Use with spring-boot-starter-data-rest.

2. Detailed explanation of annotations

1. @ SpringBootApplication: declare that SpringBoot automatically makes the necessary configuration for the program, which is equivalent to @ Configuration, @ EnableAutoConfiguration, and @ ComponentScan.

Import org.springframework.boot.SpringApplication

Import org.springframework.boot.autoconfigure.SpringBootApplication

@ SpringBootApplication / / same as @ Configuration @ EnableAutoConfiguration @ ComponentScan

Public class Application {

Public static void main (String [] args) {

SpringApplication.run (Application.class, args)

}

}

2. @ ResponseBody: indicates that the returned result of this method is directly written into HTTP ResponseBody, which is generally used when obtaining data asynchronously and is used to build the api of RESTful.

After using @ RequestMapping, the return value is usually resolved as a jump path, and the returned result is not resolved as a jump path after adding @ ResponseBody, but is written directly into the HTTP ResponseBody.

For example, if you get json data asynchronously and add @ ResponseBody, you will return json data directly.

This annotation is typically used with @ RequestMapping.

Sample code:

@ RequestMapping ("/ test")

@ ResponseBody

Public String test () {

Return "ok"

}

3. @ Controller: used to define 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).

Usually this annotation is in the class, and usually the method needs to be accompanied by the annotation @ RequestMapping.

Sample code:

@ Controller

@ RequestMapping ("/ demoInfo")

Publicclass DemoController {

@ Autowired

Private DemoInfoService demoInfoService

@ RequestMapping ("/ hello")

Public String hello (Map map) {

System.out.println ("DemoController.hello ()")

Map.put ("hello", "from TemplateController.helloHtml")

/ / hello.html or hello.ftl templates will be used for rendering and display.

Return "/ hello"

}

}

4. @ RestController: used to annotate the collection of control layer components (such as action in struts), @ ResponseBody, and @ Controller.

Sample code:

Import org.springframework.web.bind.annotation.RequestMapping

Import org.springframework.web.bind.annotation.RestController

@ RestController

@ RequestMapping ("/ demoInfo2")

Publicclass DemoController2 {

@ RequestMapping ("/ test")

Public String test () {

Return "ok"

}

}

5. @ RequestMapping: provides routing information and is responsible for mapping URL to specific functions in Controller.

6. @ EnableAutoConfiguration:Spring Boot autoconfiguration (auto-configuration): try to automatically configure your Spring application based on the jar dependencies you add.

For example, if you have HSQLDB under your classpath and you do not manually configure any database connection beans, then we will automatically configure an in-memory database.

You can add @ EnableAutoConfiguration or @ SpringBootApplication annotations to a @ Configuration class to choose automatic configuration.

If you find that specific autoconfiguration classes are applied that you don't want, you can use the exclusion attribute of the @ EnableAutoConfiguration annotation to disable them.

Search the official account of Java bosom friend, reply to "back-end interview" and send you a treasure book of Java interview questions. Pdf

7. @ ComponentScan: indicates that the scanning component will be automatically discovered by this class.

Personal understanding is equivalent to that if you scan a class with @ Component, @ Controller, @ Service, and register as Bean, you can automatically collect all Spring components, including the @ Configuration class.

We often search for beans using the @ ComponentScan annotation and import it in conjunction with the @ Autowired annotation. You can automatically collect all Spring components, including the @ Configuration class.

If it is not configured, Spring Boot will scan the classes under the startup class package and under the subpackage that use @ Service, @ Repository and other annotations.

8. @ Configuration: equivalent to the traditional xml configuration file, if some third-party libraries need to use the xml file, it is recommended that you still use the @ configuration class as the configuration main class of the project-- you can use the @ ImportResource annotation to load the xml configuration file.

9. @ Import: used to import other configuration classes.

10. @ ImportResource: used to load the xml configuration file.

11. @ Autowired: automatically import dependent bean

12. @ Service: components commonly used to modify the service layer

13. @ Repository: use the @ Repository annotation to ensure that DAO or repositories provides exception translation. DAO or repositories classes modified by this annotation will be discovered and configured by ComponetScan, and there is no need to provide XML configuration items for them.

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

15. @ Value: injects the value of the property of the Spring boot application.properties configuration. Sample code:

@ Value (value = "# {message}")

Private String message

16. @ Inject: equivalent to the default @ Autowired, but without the required attribute

17. @ Component: generally refers to components, which we can use to annotate components when they are not easy to classify.

18. @ Bean: the equivalent of XML, on top of the method, not the class, which means to generate a bean and give it to spring to manage.

19. @ AutoWired: automatically imports dependent bean. ByType mode. The configured Bean is used to complete the assembly of properties and methods. It can mark class member variables, methods and constructors and complete the work of automatic assembly. When (required=false) is added, an error is not reported even if the bean is not found.

20. @ Qualifier: when there are multiple Bean of the same type, you can specify it with @ Qualifier ("name"). Used with @ Autowired. The @ Qualifier qualifier descriptor can be injected according to the name, but it has more fine-grained control over how to select candidates. The specific usage is as follows:

@ Autowired

@ Qualifier (value = "demoInfoService")

Private DemoInfoService demoInfoService

21. @ Resource (name= "name", type= "type"): if there is no content in parentheses, byName is the default. Do something similar to @ Autowired.

Search the official account of Java bosom friend, reply to "back-end interview" and send you a treasure book of Java interview questions. Pdf

III. JPA comments

1. @ Entity:@Table (name= ""): indicates that this is an entity class. These two annotations are generally used together for jpa, but @ Table can be omitted if the table name and entity class name are the same.

2. @ MappedSuperClass: used to determine the entity that is the parent class. The attribute subclasses of the parent class can inherit.

3. @ NoRepositoryBean: a repository commonly used as a parent class. With this annotation, Spring will not instantiate the repository.

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

5. @ Id: indicates that the property is the primary key.

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

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

8. @ Transient: indicates that the attribute is not a mapping to a field of the database table, and will be ignored by the ORM framework.

If a property is not a field mapping of a database table, be sure to mark it @ Transient, otherwise, the ORM framework defaults to its annotation @ Basic.

9. @ Basic (fetch=FetchType.LAZY): tags can specify how entity attributes are loaded.

10. @ JsonIgnore: the effect is that some attributes in Java bean are ignored when json serialization, and both serialization and deserialization are affected.

11. @ JoinColumn (name= "loginId"): one-to-one: a foreign key in this table that points to another table. One-to-many: another table points to the foreign key of this table.

12. @ OneToOne, @ OneToMany, @ ManyToOne: correspond to one-to-one, one-to-many, many-to-one in the hibernate configuration file.

IV. Notes related to SpringMVC

1. @ RequestMapping:@RequestMapping ("/ path") means that the controller processes all UR L requests for "/ path".

RequestMapping is an annotation that handles request address mapping and can be used on classes or methods.

Used on a class, the method that represents all response requests in the class has this address as the parent path. The annotation has six attributes:

Params: specifies that some parameter values must be included in the request to be handled by this method.

Headers: specifies that some specified header value must be included in the request for this method to process the request.

Value: specify the actual address of the request, which can be in URI Template mode

Method: specify the method type of the request, such as GET, POST, PUT, DELETE, etc.

Consumes: specifies the type of submitted content (Content-Type) to process the request, such as application/json,text/html

Produces: specifies the content type to be returned, only if the (Accept) type in the request request header contains the specified type.

2. @ RequestParam: used before the parameters of the method.

3. @ PathVariable: path variable. Such as:

RequestMapping ("user/get/ {macAddress}")

Public String getByMacAddress (@ PathVariable String macAddress) {

/ / do something

}

The parameter should be the same as the name in curly braces.

5. Global exception handling

@ ControllerAdvice: contains @ Component. Can be scanned. Handle exceptions uniformly.

ExceptionHandler (Exception.class): used on a method to indicate that the following method is executed when this exception is encountered.

On the introduction of SpringBoot notes and its use is shared here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report