1. SpringBoot profile

1.1 Analysis of the advantages and disadvantages of the original Spring

1.1.1 Analysis of Spring’s advantages

Spring is a lightweight alternative to Java Enterprise Edition (javeEE). Instead of developing heavyweight Enterprise Javabeans (EJBs), Spring provides a relatively simple way for Enterprise Java development through dependency injection and section-oriented programming with Plain Old Java Objects, POJO implements EJB functionality.

1.1.2 Analysis of Spring’s shortcomings

While Spring’s component code is lightweight, its configuration is heavyweight.

Whether it was xmL-based configuration from the start, annotation-based component scanning introduced by Spring2.5, or Java-based configuration introduced by Spring 3.0, these represent additional costs at development time.

Because there is a mental switch between thinking about Spring configurations and solving business problems, and even pointless arguments about how to configure better, writing configurations takes time away from writing application logic. Like all frameworks, Spring is practical, but at the same time it demands a lot in return.

In addition, project dependency management is also a time consuming thing. When setting up the environment, we need to analyze the coordinates of which libraries to import, and also the coordinates of other libraries that depend on it. Once we choose the wrong version of the dependency, the resulting incompatibility problem will seriously hinder the development progress of the project.

1.2 Overview of SpringBoot

SpringBoot improves and optimizes the above shortcomings of Spring, based on the idea that convention is better than configuration, so that developers do not have to switch between configuration and logical business, and devote themselves to the code writing of logical business, thus greatly improving the efficiency of development and shortening the project cycle to a certain extent.

1.2.1 Characteristics of SpringBoot

  • SpringBoot is not an enhancement to Spring’s capabilities, but rather provides a way to quickly build Spring
  • Out of the box, there is no code generation and no XML configuration. You can also modify the default values to meet specific requirements
  • It provides non-functional features common in large projects, such as embedded servers (embedded Tomcat without deploying WAR files), security, metrics, health checks, external configuration, and so on

1.2.2 Core Functions of SpringBoot

  • Startup dependencies Startup dependencies are essentially a Maven Project Object Model (POM) that defines transition-dependent dependencies to other libraries, which together support functionality. To put it simply, a starter dependency is a bundle of coordinates that have some functionality and provide some default functionality.
  • Automatic configuration Of Spring Boot automatic configuration of Spring Boot is a run-time (or, more accurately, application startup) process that considers many factors to determine which Spring configuration should and should not be used. Spring does this automatically.

The principle of starting dependencies and automatic configuration will be explained in detail later.

2. SpringBoot instance

2.1. Create a Simple SpringBoot instance

Let’s create a simple example of a Springboot-based Web project using Maven.

2.1.1. Create a project

Note: Although you are creating a Web project, SpringBoot has Tomcat embedded in it, so the jar package is chosen here.

2.1.2. Adding dependencies

Add SpringBoot dependencies to the POM.xml file

The < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > The < modelVersion > 4.0.0 < / modelVersion > < groupId > com. Neusoft < / groupId > < artifactId > boot < / artifactId > < version > 0.0.1 - the SNAPSHOT < / version > <! -- Inherits spring-boot-dependencies from Spring Boot's parent. The parent dependencies manage all versions of dependencies in a Spring Boot project and do not need to write version numbers by default. <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.3.RELEASE</version> </parent> <dependencies> <! -- Spring-boot-starter is the core spring Boot initiator. By importing the officially provided starter, you can import all the relevant jars in this module. The official naming convention for the starter module is: spring-boot-starter module name Therefore, the following configuration will import the Jars related to Web development and automatically manage the version information. --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>Copy the code

2.1.3. Add the project master startup class

Create the helloApplication.java file in the classpath

package com.neusoft.boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class HelloApplication { public static void main(String[] args) { SpringApplication.run(HelloApplication.class, args); }}Copy the code

Note:

  1. The @SpringBootApplication annotation specifies this class as the program entry class for SpringBoot.
  2. The default assembly rule for beans in a SpringBoot project is to scan from top to bottom based on the package location of the entry class. For example, if the DemoApplication package is com.neusoft. Demo; The com.neusoft. Demo package and all its subpackages will be scanned automatically, otherwise it will not be scanned! Therefore, the SpringBoot program entry class should be placed above the mapper, Service package.
  1. The run method in the SpringApplication class initializes the creation of the current SpringBoot project process.

2.1.4. Create the Controller

Create the Controller package under the helloApplication.java package, and then create the Controller.

package com.neusoft.boot.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @restController public class HelloController {@requestMapping ("/hello") public String say(){ The client will receive json data return "Hello..." ; }}Copy the code

The @RestController annotation identifies the current class as a Controller component and responds directly to json data.

2.1.5. Test

Executing the entry method of the HelloApplication class, the Run method in the SpringApplication class launches the current SpringBoot project.

Tomcat started on port(s): 8080 (HTTP) with context path "Started DemoApplication in 4.292 seconds (JVM running for 5.15)Copy the code

When the preceding information is displayed on the console, the SpringBoot project is successfully started. Enter a URL in the address bar to test access:

Note: SpringBoot is embedded with Tomcat, so you only need to run the main boot class of the SpringBoot project.

2.1.6. Project directory structure

2.2. Create the project using Spring Initializr

In the above example, we manually set up a SpringBoot framework ourselves. In fact, for rapid development, SpringBoot officially provides us with an initializer that can guide us to quickly build a SpringBoot project.

2.2.1. Use official tools to generate projects

IO /projects/sp… There is a link to Spring Initializr at the bottom of the site.

Click this link to enter the project guide page:

Note:

  1. On the left side of the guide page, set the project properties and version information. The right part sets the dependent JAR packages that the project adds.
  2. Packaging selects Jar format. (Because SpringBoot has a built-in server, there is no need to type a WAR package)
  1. Because we want to create a Web project, we add the Spring Web dependency module.
  2. Finally, click the “GENERATE” button to GENERATE the entire project.

2.2.2. Project directory structure

Start by using the IDE import project (here using STS to import the Maven project).

Note: MVNW is a Maven Wrapper script that allows you to run Maven commands without installing Maven or with incompatible versions of Maven.

2.2.3. Pom. XML file

<? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > <! --> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> The < artifactId > spring - the boot - starter - parent < / artifactId > < version > 2.3.3. RELEASE < / version > < relativePath / > <! -- lookup parent from repository --> </parent> <! --> <groupId>com.neusoft</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name> Demo </name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> <! - engineering character encoding set - > < project. Build. SourceEncoding > utf-8 < / project. Build. SourceEncoding > <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion>  </exclusions> </dependency> </dependencies> <! GroupId >org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>Copy the code

2.2.4. Project master startup class

package com.neusoft.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}Copy the code

2.2.5. Create the Controller

Create the Controller package under the demoApplication.java package, and then create the Controller.

package com.neusoft.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
    @RequestMapping("/hello")
    public String say() {
        return "hello...";
    }
}
Copy the code

2.2.6. Test

Execute the entry method of the DemoApplication class, and then test the access by entering the URL in the address bar.

2.3. Create the project using STS

2.3.1. Create the Spring Starter Project

2.3.2. Adding project information

Note: Add some information required by the Maven project here

2.3.3. Add version and dependency information

Note: Add SpringBoot version information and added dependency information here. Then click “Finish”.

2.3.4. Generate a SpringBoot project

After the project is created, we see that the project created is exactly the same as the project created using Spring Initializr.

2.4. SpringBoot hot deployment

We repeatedly modified class in the development, pages and other resources, to come into force after every change is a need to restart the, so every start very troublesome, waste a lot of time, we can not restart after modifying code can take effect, in pom. Add the following XML configuration can realize such functions, we call it hot deployment.

<! > <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency>Copy the code

2.5. Cross-domain processing of SpringBoot

In addition to using traditional filters to set up cross-domain processing configurations, SpringBoot provides us with two cross-domain processing options:

  1. Configure a Controller to cross domains using the @crossorigin annotation.
// Just use the @crossorigin annotation on this Controller to achieve cross-domain access, @crossorigin ("*") @restController Public Class DeptController {//... }Copy the code
  1. Implement the addCorsMappings method in the WebMvcConfigurer interface, in which global cross-domain processing is configured. Add the WebMvcConfig class to the project. With the @Configuration annotation, this class becomes a Spring container class, and the Configuration in this class is automatically loaded when the project starts.
package com.neusoft.demo; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void AddCorsMappings (CorsRegistry registry) {/* * addMapping: Configure the connection routes that can be cross-domain, which can be any configuration, and which can be specific to the connection requests. * allowCredentials: whether cookies are enabled * allowedMethods: Allowed request methods, such as POST, GET, PUT, and DELETE. * allowedOrigins: specifies a URL that is allowed to be accessed. One or more items can be fixed. * allowedHeaders: Specifies an allowed request header. * maxAge: AddMapping ("/**").allowedorigins ("*").allowcredentials (true).allowedMethods("*") .allowedHeaders("*") .maxAge(36000); }}Copy the code

2.6.@RequestBody implements parameter serialization

When the front-end uses AJAX POST request, it needs to serialize the request parameters, otherwise SpringMVC cannot receive the submission parameters.

/ / qs module the stringify method is used to realize the post submission when the parameters of the serialization enclosing $axios. Post (' http://localhost:8080/hello ', this. $qs. Stringify (user))...Copy the code

In SpringBoot, you can use the @RequestBody annotation to serialize parameters for post submissions on the server side. In this way, the front-end POST request can submit the JSON object directly.

@requestBody ("/hello") public String say(@requestBody User User) {system.out.println (User); return "hello..." ; }Copy the code
let user = {
    userId: 1,
    userName: 'zhangsan',
    password: '123'
};
axios.post('http://localhost:8080/elm/hello',user)
    .then(response => {
        console.log(response.data);
    }).catch(error => {
        console.log(error);
    });
Copy the code

The @RequestBody annotation is so powerful that it can even accept json arrays directly.

@requestMapping ("/hello") public String say(@requestBody List<User> List) {for(User User: list) { System.out.println(user); } return "hello..." ; }Copy the code
Let userArr = [{userId: 1, userName: 'zhang 3', password: '123'}, {userId: 2, userName:' li 4 ', password: }, {userId: 3, userId: 3, password: '999' }] axios.post('http://localhost:8080/elm/hello', userArr) .then(response => { console.log(response.data); }).catch(error => { console.log(error); });Copy the code

Note: the @requestBody annotation does not support get requests

3.SpringBoot principle analysis

3.1. Analysis of starting dependence principle

3.1.1. Analysis of spring – the boot – starter – the parent

Press Ctrl and click spring-boot-starter-parent in pom. XML to jump to pom. XML of spring-boot-starter-parent.

<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> < version > 2.3.3. RELEASE < / version > < relativePath >.. /.. /spring-boot-dependencies</relativePath> </parent>Copy the code

Press Ctrll and click Spring-boot-starter-dependencies in PM. XML to jump to PM. XML of spring-boot-starter-dependencies.

< properties > < activemq. Version > 5.15.3 < / activemq version > < antlr2. Version > 2.7.7 < / antlr2 version > < appengine - SDK version > 1.9.63 < / appengine - SDK version > < Artemis. Version > 2.4.0 < / Artemis. Version > < aspectj version > 1.8.13 < / aspectj version > < assertj. Version > 3.9.1 < / assertj version > < atomikos version > 4.0.6 < / atomikos version > < bitronix. Version > 2.1.4 < / bitronix version > . < build - helper - maven - the plugin version > 3.0.0 < / build - helper - maven - plugin. Version > The < byte - buddy. Version > 1.7.11 < / byte - buddy. Version >... . . </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> < artifactId > spring - the boot < / artifactId > < version > 2.3.1. RELEASE < / version > < / dependency > < the dependency > < the groupId > org. Springframework. Boot < / groupId > < artifactId > spring - the boot - test < / artifactId > < version > 2.3.3. RELEASE < / version > </dependency> ... . . </dependencies> </dependencyManagement> <build> <pluginManagement> <plugins> <plugin> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-plugin</artifactId> <version>${kotlin.version}</version> </plugin> <plugin> <groupId>org.jooq</groupId> <artifactId>jooq-codegen-maven</artifactId> <version>${jooq.version}</version> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> < version > 2.3.3. RELEASE < / version > < / plugin >... . . </plugins> </pluginManagement> </build>Copy the code

< span style = “box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 14px! Important; word-break: break-word! Important;” So our SpringBoot project inherits spring-boot-starter-parent with version locking and other configurations. So the role of initial dependency is to carry out the transfer of dependency.

3.1.2. Analysis of spring – the boot – starter – web

Press Ctrll and click Spring-boot-starter-web in POM. XML to jump to pom. XML of spring-boot-starter-web. The XML configuration is as follows (only some important configurations are extracted) :

<? The XML version = "1.0" encoding = "utf-8"? > < project xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" > < modelVersion > 4.0.0 < / modelVersion > < the parent > < groupId > org. Springframework. Boot < / groupId > The < artifactId > spring - the boot - starters < / artifactId > < version > 2.3.3. RELEASE < / version > < / parent > <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.3.3.RELEASE</version> <name>Spring Boot Web Starter</name> <dependencies> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> < version > 2.3.3. RELEASE < / version > < scope > compile < / scope > < / dependency > < the dependency > <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-json</artifactId> < version > 2.3.3. RELEASE < / version > < scope > compile < / scope > < / dependency > < the dependency > <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> < version > 2.3.3. RELEASE < / version > < scope > compile < / scope > < / dependency > < the dependency > < the groupId > org. Hibernate. The validator < / groupId > < artifactId > hibernate validator - < / artifactId > < version > 6.0.9. The Final < / version > <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId> Spring-web </artifactId> <version>5.2.8.RELEASE</version> <scope>compile</scope> </dependency> <dependency> < the groupId > org. Springframework < / groupId > < artifactId > spring - webmvc < / artifactId > < version > 5.2.8. RELEASE < / version > <scope>compile</scope> </dependency> </dependencies> </project>Copy the code

From the above spring – the boot – starter – web pom. In XML, we can find that spring – the boot – starter – web is > web development to use spring – web, such as spring – webmvc coordinates the “package”, In this way, as long as our project introduces the coordinates of spring-boot-starter-Web starting dependence, we can carry out Web development, which also reflects the function of dependency transfer.

3.2. Automatic configuration principle analysis

Hold Ctrll and click to view the annotation @SpringBootApplication on the DemoApplication bootstrap class

@SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}Copy the code

Annotate the @SpringBootApplication source code

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {  //...  }
Copy the code

@enableAutoConfiguration: SpringBoot automatic Configuration enabled @ComponentScan: Define scan paths to identify classes that need to be assembled and automatically assemble them into the Spring container

3.3. Processor configuration principle analysis

Hold Ctrll and click the annotation @RestController on the processor class UserController

@RestController
public class UserController { }
Copy the code

Annotate the @restController source code

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController { //... }
Copy the code

You can see that the @restController annotation is equivalent to @Controller+ @responseBody

4.SpringBoot project configuration file

SpringBoot is convention based, so many configurations have default values, but if you want to replace the defaults with your own configuration, you can use the SpringBoot configuration file.

There are two types of SpringBoot configuration files: Properties file and YML file. By default, SpringBoot loads either application.properties or application.yml files from the Resources directory.

4.1. The application. The properties configuration file

Here is an example of the application.properties configuration file:

Server.servlet. context-path=/elm ## Set SpringBoot log output level (error, warn, info, the debug) logging.level.org.springframework=debugCopy the code

4.2.application.yml configuration file

YML file format is a file format written by YAML Aint Markup Language. YAML is an intuitive data serialization format that can be recognized by computers and easily read by humans. It is easy to interact with scripting languages and can be imported by different programming languages that support YAML libraries. For example: C/C++, Ruby, Python, Java, Perl, C#, PHP, etc. YML files are data-centric and much more concise than traditional XML.

The extension name of the YML file can be. YML or. Yaml.

Here is an example of the application.yml configuration file:

server:
    port: 8080
    servlet:
        context-path: /elm
logging:
    level:
        org.springframework: debug
Copy the code

Basic syntax of YML files:

  1. Case sensitivity
  2. Use indentation to indicate hierarchy (the number of Spaces indented is not important, as long as elements of the same rank are left aligned)
  1. Indent does not allow tabs, only Spaces
  2. A colon must be followed by a space
  1. Use # as a comment

4.3. Querying SpringBoot configuration Information

As mentioned above, the main purpose of SpringBoot configuration files is to modify configuration information, but where to query the key during configuration? We can refer to the official documentation of SpringBoot: docs. Spring. IO /spring-boot… Common configurations are summarized as follows:

# QUARTZ SCHEDULER (QuartzProperties) spring.quartz.jdbc.initialize-schema=embedded # Database schema initialization mode. spring.quartz.jdbc.schema=classpath:org/quartz/impl/jdbcjobstore/tables_@@platform@@.sql # Path to the SQL file to  use to initialize the database schema. spring.quartz.job-store-type=memory # Quartz job store type. spring.quartz.properties.*= # Additional Quartz Scheduler properties. # ---------------------------------------- # WEB PROPERTIES # ---------------------------------------- # EMBEDDED SERVER CONFIGURATION (ServerProperties) server.port=8080 # Server HTTP port. server.servlet.context-path= # Context path of the application. server.servlet.path=/ # Path of the main dispatcher servlet. # HTTP encoding (HttpEncodingProperties) spring.http.encoding.charset=UTF-8 # Charset of HTTP requests and responses. Added to the "Content-Type" header if not set explicitly. # JACKSON (JacksonProperties) spring.jackson.date-format= # Date format string or a fully-qualified date  format class name. For instance, `yyyy-MM-dd HH:mm:ss`. # SPRING MVC (WebMvcProperties) spring.mvc.servlet.load-on-startup=-1 # Load on startup priority of the dispatcher servlet. spring.mvc.static-path-pattern=/** # Path pattern used for static resources. spring.mvc.view.prefix= # Spring MVC view prefix. spring.mvc.view.suffix= # Spring MVC view suffix. # DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) spring.datasource.driver-class-name= # Fully qualified name of the JDBC driver. Auto-detected based on the URL by default. spring.datasource.password= # Login password of the database. spring.datasource.url= # JDBC URL of the database. spring.datasource.username= # Login username of the database.Copy the code

4.4. @ Value annotation

We can map values in a configuration file to properties of a Spring-managed Bean using the @Value annotation.

RestController Public Class DeptController {// Server. port is a SpringBoot configuration file. @value ("${server.port}") private int port; @Autowired private DeptService deptService; @requestMapping ("/listDept") public List<Dept> listDept(){system.out.println (" port: "+port); return deptService.listDept(); }}Copy the code

You can use the @Value annotation to get the Value in the SpringBoot configuration file by placing it on a property.

5. MyBatis SpringBoot integration

5.1. Add MyBatis dependencies

<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> < version > 2.0.1 < / version > < / dependency > < the dependency > < groupId > mysql < / groupId > < artifactId > mysql connector - Java < / artifactId > < version > 5.1.6 < / version > < scope > runtime < / scope > < / dependency >Copy the code

5.2. Add MyBatis configuration

Configure MyBatis information in the application.properties configuration file

Server port = 8080 server. The servlet. The context path = / elm logging.level.org.springframework=debug # # configuration mapper output log level Spring logging.level.com.neusoft.demo.mapper=debug # # configuration data source information. The datasource. The username = root spring. The datasource. Password = 123 spring.datasource.url=jdbc:mysql://localhost:3306/elm?characterEncoding=utf-8 Spring.datasource. Driver-class-name = com.mysql.jdbc.driver ## Configure mapper mapping file path Mybatis. Type-aliases-package =com.neusoft. DemoCopy the code

You can also use the application. Yml configuration file to configure MyBatis:

server:
    port: 8080
    servlet:
        context-path: /elm
logging:
    level:
        org.springframework: debug
        com.neusoft.demo.mapper: debug
spring:
    datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/elm?characterEncoding=utf-8
        username: root
        password: 123
mybatis:
    mapper-locations: classpath:mapper/*.xml
    type-aliases-package: com.neusoft.demo.po
Copy the code

5.3. Create a Mapper Interface

@Mapper
public interface DeptMapper {
    @Select("select * from dept order by deptno")
    public List<Dept> listDept();
}
Copy the code

Note: This Mapper interface must be identified with @mapper

5.4. Create the Service interface and implementation class

public interface DeptService {
    public List<Dept> listDept();
}
Copy the code
@Service public class DeptServiceImpl implements DeptService{ @Autowired private DeptMapper deptMapper; @Override public List<Dept> listDept() { return deptMapper.listDept(); }}Copy the code

5.5. To create the controller

@RestController public class DeptController { @Autowired private DeptService deptService; @RequestMapping("/listDept") public List<Dept> listDept(){ return deptService.listDept(); }}Copy the code

5.6. Test

<script src="https://unpkg.com/axios/dist/axios.js"></script>
<script>
    axios.post('http://localhost:8080/elm/listDept')
        .then(response => {
            console.log(response.data);
        }).catch(error => {
            console.log(error);
        });    
</script>
Copy the code

This chapter homework

  1. What’s the difference between SpringBoot and SpringMVC?
  2. What are the characteristics of SpringBoot?
  1. Describe the core functions of SpringBoot.
  2. How about the @requestBody annotation?
  1. Describe the basic syntax of yML files.
  2. What is Spring Boot Stater?
  1. What is an embedded server? Why do we use embedded servers?
  2. Programming problem:
    1. Implement a login case using the SpringBoot+MyBatis integration framework.
    2. Use the pattern of front and back end separation.
    1. The server side must have the data layer component, the business layer component, the control layer component.
    2. The data layer component uses the MyBatis framework to operate on the database.
    1. The control-layer component returns JSON data to the front end.
    2. The front-end uses Ajax requests and determines whether the login is successful by the JSON data returned by the server.

Green hills do not change, green water flow! Hope to help you!!