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

Detailed introduction and explanation of SpringBoot notes

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

Share

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

The main content of this article is "detailed introduction and explanation of SpringBoot notes". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn the detailed introduction and explanation of SpringBoot notes.

1. Annotations list

@ SpringBootApplication: contains @ ComponentScan, @ Configuration, and @ EnableAutoConfiguration annotations.

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

@ Configuration is equivalent to spring's XML configuration file; you can check type safety with Java code.

@ EnableAutoConfiguration automatic configuration.

@ ComponentScan component scan, you can automatically discover and assemble some Bean.

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

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

@ Autowired imports automatically.

@ PathVariable gets the parameter.

@ JsonBackReference solves the problem of nested outer chains.

@ RepositoryRestResourcepublic is used with spring-boot-starter-data-rest.

2. Detailed explanation of annotations

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

Package com.example.myproject;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication / / same as @ Configuration @ EnableAutoConfiguration @ ComponentScanpublic class Application {public static void main (String [] args) {SpringApplication.run (Application.class, args);}}

@ ResponseBody: indicates that the returned result of this method is directly written into HTTP response body, 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") @ ResponseBodypublic String test () {return "ok";}

Controller: used to define the controller class. In the spring project, the controller is responsible for forwarding the URL request sent by the user 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"); / / will render the display using hello.html or hello.ftl templates. Return "/ hello";}}

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

Sample code:

Package com.kfit.demo.web;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";}}

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

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

@ 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 package where the startup class is located and under the subpackage that use annotations such as @ Service,@Repository.

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

Import: used to import other configuration classes.

ImportResource: used to load the xml configuration file.

@ Autowired: automatically imports dependent bean

@ Service: components commonly used to decorate the service layer

@ Repository: use the @ Repository annotation to ensure that DAO or repositories provides exception translation. The 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.

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

Value: the value of the property that is injected into the Spring boot application.properties configuration. Sample code:

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

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

Component: generally refers to components. We can use this annotation to annotate components when they are not easy to classify.

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

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.

@ 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

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

III. JPA comments

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

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

NoRepositoryBean: a repository that is generally used as a 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 the property is the primary key.

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

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

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. @ Basic (fetch=FetchType.LAZY): tags can specify how entity attributes are loaded

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

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.

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

IV. Notes related to springMVC

@ 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

RequestParam: used before the parameters of the method.

@ RequestParam

String a = request.getParameter ("a").

@ PathVariable: path variable. Such as

RequestMapping ("user/get/mac/ {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.

At this point, I believe you have a deeper understanding of the "detailed introduction and explanation of SpringBoot notes". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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

Internet Technology

Wechat

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

12
Report