Spring Boot [Quick Start]

Spring Boot overview

Build Anything with Spring Boot:Spring Boot is the starting point for building all Spring-based applications. Spring Boot is designed to get you up and running as quickly as possible, with minimal upfront configuration of Spring.

The above is a quote from the official website, probably saying: Spring Boot is the starting point for all projects developed based on Spring. Spring Boot is designed to get you up and running with Spring applications as fast as possible and with as few configuration files as possible.

What is Spring Boot

  • It uses the concept of "habit over configuration" (there are a lot of configurations in the project, plus there is a built-in habit configuration so you don't have to) to get your project up and running quickly.
  • It is not a new framework, but is configured with many frameworks by default. Just like Maven integrates all jar packages, Spring Boot integrates all frameworks (quoted from: springboot (1): Getting Started - Pure smile )

What are the benefits of using Spring Boot

Looking back on our previous SSM projects, the construction process is still relatively cumbersome, requiring:

  • 1) Configure web.xml, load spring and spring mvc
  • 2) Configure database connection, configure log file
  • 3) Configure the home to read the configuration file and open the annotation
  • 4) Configure the mapper file
  • .....

Using Spring Boot to develop projects requires only a few configurations to build a Web project, and IDEA can be used to automatically generate and generate, which is so cool...

  • Key points: simple, fast and convenient construction of projects; no-configuration integration of mainstream development frameworks; greatly improved development and deployment efficiency.

Spring Boot Quick Setup

Step 1: Create a new project

Select Spring Initializr, then select the default url and click [Next]:

Then modify the project information:

Check Web Templates:

Select the location of the project and click [Finish]:

If it is the first time to configure Spring Boot, you may need to wait for a while for IDEA to download the corresponding dependency package. The default created project structure is as follows:

The project structure still looks quite refreshing. There are a lot of configuration files missing. Let's take a look at what is generated by default:

  • SpringbootApplication: a class with a main() method to start the application
  • SpringbootApplicationTests: An empty Junit test that loads a Spring application context using Spring Boot dictionary configuration capabilities
  • application.properties: an empty properties file, you can add configuration properties as needed
  • pom.xml: Maven build specification file

Step 2: HelloController

Create a new [HelloController] under the [cn.wmyskxz.springboot] package:

package cn.wmyskxz.springboot;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 测试控制器
 *
 * @author: @我没有三颗心脏
 * @create: 2018-05-08-下午 16:46
 */
@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello() {
        return "Hello Spring Boot!";
    }
}
  • **@RestController annotation:** This annotation is a combined version of @Controller and @ResponseBody annotations

Step 3: Start Spring Boot with IDEA

We go back to the SpringbootApplication class, and then right-click to run:

  • Note : The reason why we did not manually configure the Tomcat server in the above project is because Spring Boot has built-in Tomcat

Wait for a while and you will see the following message of successful operation:

You can see that our Tomcat is running on port 8080, let's /hellotry to access the " " address:

You can see that the page successfully displays the information we returned.


Parse the Spring Boot project

This part is referenced from: Spring Boot Dry Goods Series (1) Elegant Introduction - Dudu Independent Blog

Parse the pom.xml file

Let's take a look at what's special in the default generated pom.xml file:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.wmyskxz</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </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>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

We can see a relatively unfamiliar tag <parent>, this tag is configuring Spring Boot's parent dependencies:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

With this, the current project is the Spring Boot project, and spring-boot-starter-parent is a special starter, which is used to provide related Maven default dependencies. After using it, the version tag can be omitted for commonly used package dependencies. .

Regarding which jar package dependencies are provided by Spring Boot, we can check the local Maven repository: \repository\org\springframework\boot\spring-boot-dependencies\2.0.1.RELEASE\spring-boot-dependencies-2.0.1 .RELEASE.pom file to view, quite long...

Application entry class

Spring Boot projects usually have an entry class named *Application, and the entry class has a main method, which is actually the entry method of a standard Javay application.

**@SpringBootApplication* * is the core annotation of Spring Boot. It is a composite annotation that combines: **@Configuration , @EnableAutoConfiguration, @ComponentScan; ** If you do not use the @SpringBootApplication annotation, you can also use these three annotations replace.

  • Among them, **@EnableAutoConfiguration allows Spring Boot to automatically configure the current project according to the jar package dependencies in the classpath**, for example, adding spring-boot-starter-web dependencies will automatically add Tomcat and Spring MVC dependencies, then Spring Boot automatically configures Tomcat and Spring MVC.
  • Spring Boot will also automatically scan the same-level package of the class where @SpringBootApplication is located and the beans in the lower-level package , so it is recommended to configure the entry class under the package name of group ID + arctifactID (here is the cn.wmyskxz.springboot package)

Spring Boot configuration file

Spring Boot uses a global configuration file application.properties or application.yml, which is placed in the [src/main/resources] directory or under /config in the classpath.

Spring Boot not only supports regular properties configuration files, but also yaml language configuration files. yaml is a data-centric language with object-oriented features when configuring data.

The role of Spring Boot's global configuration file is to modify the configuration values ​​of some default configurations.

  • Simple example

When we also set the default port of Tomcat to 8080 and change the default access path from " /" to " /hello", the difference between using the properties file and the yml file is shown in the figure above.

  • Note: yml needs to :add a space after " ", fortunately IDEA supports the format of yml file well and has good code hints;
  • We can configure multiple properties ourselves

We directly delete the files with the .properties suffix, use the .yml file for simple configuration, and then use @Value to get the configuration properties:

Restart Spring Boot and enter the address: localhost:8080/hello to see the correct result:

  • Note: We do not specify the type of the attribute in the yml file, but define it when it is used.

You can also use the current configuration in a configuration file:

Still get the correct result:

  • Problem: Writing config files like this is cumbersome and can bloat the class because there are so many @Value annotations.
  • Package configuration information

We can encapsulate the configuration information into a class, first add a student prefix before our name and age, and then create a new StudentProperties class to encapsulate this information, and use the two annotations:

  • @Component: indicates that the current class is a Java Bean
  • @ConfigurationProperties(prefix = "student"): Indicates obtaining configuration information with a prefix of sutdent

So we can use it in the controller, restart to get the correct information:

Spring Boot hot deployment

In the current Spring Boot project, when any modification occurs, we need to restart to get the effect correctly, which will be slightly troublesome. Spring Boot provides a hot deployment method. When any class is found to have changed, it will be The latest class will be loaded into the virtual machine through the JVM class loading method, so that the modified effect can be seen without restarting.

  • The practice is also very simple, just modify pom.xml!

We can add a dependency to pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional> <!-- 这个需要为 true 热部署才有效 -->
</dependency>

Restart Spring Boot, and then modify any code to observe the automatic restart of the console:

About how to configure hot deployment in IDEA: Portal


Spring Boot usage

The simple construction of the Spring Boot project has been completed above. We only need to make some simple settings and write a HelloController to run it directly. Don't be too simple... Next, let's take a deeper look at the use of Spring Boot.

Spring Boot supports JSP

The default view support of Spring Boot is the Thymeleaf template engine, but we are not familiar with this, what if we still want to use JSP?

  • Step 1: Modify pom.xml to add support for JSP files
<!-- servlet依赖. -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>

<!-- tomcat的支持.-->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>
  • Step 2: Configure where to try to redirect JSP files

Modify the application.yml file to redirect our JSP file to the /WEB-INF/views/ directory:

  • Step 3: Modify HelloController

Modify the @RestController annotation to @Controller, and then modify the hello method to:

  • Step 4: Create a new hello.jsp file

Create the webapp, WEB-INF, views directories in sequence under the [src/main] directory, and create a hello.jsp file:

  • Step 5: Refresh the webpage

Because we have deployed the hot deployment function, we only need to wait for the console restart information to complete and then refresh the web page to see the correct effect:

  • Regarding 404, running the project with spring-boot:run solves it:

Integrate MyBatis

  • Step 1: Modify pom.xml to add support for MySql and MyBatis
 
<!-- mybatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>
<!-- mysql -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.21</version>
</dependency>
  • Step 2: Add database link parameters

Here we directly use the student table created earlier:

  • Step 3: Create the Student entity class and the StudentMapper mapping class

Create a new [pojo] package under [cn.wmyskxz.springboot], and then create a Student class under it:

public class Student {

    private Integer id;
    private Integer student_id;
    private String name;
    private Integer age;
    private String sex;
    private Date birthday;

    /* getter and setter */
}

Create a new [mapper] package under [cn.wmyskxz.springboot], and then create a StudentMapper mapping class under it:

package cn.wmyskxz.springboot.mapper;

import cn.wmyskxz.springboot.pojo.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface StudentMapper {

    @Select("SELECT * FROM student")
    List<Student> findAll();
}
  • Step 4: Write StudentController

Create a new [controller] package under [cn.wmyskxz.springboot], and then create a StudentController under it:

package cn.wmyskxz.springboot.controller;

import cn.wmyskxz.springboot.mapper.StudentMapper;
import cn.wmyskxz.springboot.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * Student 控制器
 *
 * @author: @我没有三颗心脏
 * @create: 2018-05-08-下午 20:25
 */
@Controller
public class StudentController {

    @Autowired
    StudentMapper studentMapper;

    @RequestMapping("/listStudent")
    public String listStudent(Model model) {
        List<Student> students = studentMapper.findAll();
        model.addAttribute("students", students);
        return "listStudent";
    }
}

Step 5: Write the listStudent.jsp file

Let's simplify the JSP file and only display the data for two fields:

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<table align='center' border='1' cellspacing='0'>
    <tr>
        <td>id</td>
        <td>name</td>
    </tr>
    <c:forEach items="${students}" var="s" varStatus="st">
        <tr>
            <td>${s.id}</td>
            <td>${s.name}</td>
        </tr>
    </c:forEach>
</table>
  • Step 6: Restart the server to run

Because a new dependency package is added to pom.xml, restarting the server automatically has no effect. We need to restart it manually, and then enter the address: localhost:8080/listStudent to see the effect:

above.


References:

how2j.cn-Spring Boot series of tutorials

Welcome to reprint, reprint please indicate the source!
@I don't have three hearts
CSDN blog: http://blog.csdn.net/qq939419061
short book: http://www.jianshu.com/u/a40d61a49221

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325899480&siteId=291194637