Spring Boot "Quick Start"

Source: Internet
Author: User
Tags tomcat server spring initializr

Spring Boot Overview

Build anything with Spring Boot: Spring Boot is the starting point to building all spring-based applications. Spring Boot is designed to get running as quickly as possible, with minimal upfront configuration of spring.

Here is a quote from the official website, presumably: Spring Boot is the starting point for all spring-based projects. Spring Boot is designed to allow you to run the spring application as quickly as possible and to minimize your configuration files.

What is Spring Boot
    • It uses "habits better than Configuration" (there are a lot of configurations in the project, plus a built-in configuration that lets you do not need to) to get your project up and running quickly.
    • It's not a new framework, it's a default configuration of how many frameworks are used, just as Maven integrates all the jar packages, and Spring Boot integrates all the frameworks (citation: Springboot (a): Introductory article-Pure Smile)
What are the benefits of using Spring Boot?

Looking back at our previous SSM project, the build process is cumbersome and requires:

    • 1) Configure Web. XML to load spring and spring MVC
    • 2) Configure database connection, configuration log file
    • 3) Configure home read in config file, open annotations
    • 4) Configure the Mapper file
    • .....

Using Spring Boot to develop a project requires very few configurations to build a Web project, and using idea can generate the build automatically, which is really cool ...

    • Focus: Simple, fast, easy to build projects, the mainstream development framework of the non-configuration integration, greatly improve the development and deployment efficiency.
Spring Boot Quick Build First step: New project

Select Spring initializr and select the default URL to click "Next":

Then modify the information for the project:

Tick the Web Template:

Select the location of the project and click "Finish":

If you are configuring Spring Boot for the first time, you may need to wait for the idea to download the appropriate dependency package, and the default created project structure is as follows:

The project structure still looks very refreshing, with a lot less configuration files, let's see what the default build is:

    • Springbootapplication: A class with the main () method to start the application
    • Springbootapplicationtests: An empty Junit test that loads a spring application context that uses the Spring Boot dictionary configuration feature
    • Application.properties: An empty properties file, you can add configuration properties as needed
    • Pom.xml:Maven Building the documentation
Step Two: 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 */@RestControllerpublic class HelloController {    @RequestMapping("/hello")    public String hello() {        return "Hello Spring Boot!";    }}
    • * * @RestController NOTE: * * This note is a fit version of @Controller and @ResponseBody annotations
Step three: Use idea to start Spring boot

Let's go back to the Springbootapplication class and then right-click to run:

    • Note : We did not manually configure the Tomcat server in the above project because the Spring Boot built-in Tomcat

Wait a moment and you'll see the following tips for running successfully:

Can see our Tomcat running on port 8080, let's go to the " /hello " address and try it out:

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

Parsing the Spring Boot project

This section is for reference from: Spring Boot Dry Series (i) elegant introductory article-Doodle Independent Blog

Parsing pom.xml files

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 PR         Oject for Spring boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.release</version&gt        ; <relativePath/> <!--lookup parent from repository to </parent> <properties> <pro Ject.build.sourceencoding>utf-8</project.build.sourceencOding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.ve rsion>1.8</java.version> </properties> <dependencies> <dependency> < Groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid&gt        ;            </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> &LT;/DEP endency> </dependencies> <build> <plugins> <plugin> < Groupid>org.springframework.boot</groupid> <artifactid>spring-boot-maven-plugin</artifact id> </plugin> </plugins> </build></project>

We can see a somewhat unfamiliar label <parent> , this tag is in the configuration of Spring Boot's parent dependency:

<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, Spring-boot-starter-parent is a special starter, it is used to provide the relevant Maven default dependency, after using it, the usual package dependencies can save Version label.

We can view the local Maven repository for the dependencies on which jar packages are provided by the specific Spring Boot: \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

The Spring Boot project usually has an entry class called *application, which has a main method in the entry class, which is actually a standard entry method for Javay applications.

* * @SpringBootApplication * * is the core note of Spring Boot and is a combination of annotations that combines: * * @Configuration, @EnableAutoConfiguration, @ componentscan;** You can use these three annotations instead of @SpringBootApplication annotations.

    • where * * @EnableAutoConfiguration let Spring Boot automatically configure the current project based on the jar package dependencies in the classpath * *, for example, adding a spring-boot-starter-web dependency and automatically adding Tomcat and spring MVC, Spring Boot will automatically configure Tomcat and spring MVC.
    • Spring Boot also automatically scans the siblings of the @SpringBootApplication class and the beans in the sub-packages , so the Ingress class is recommended to be configured under the Grounpid + Arctifactid combination of packages (CN). Wmyskxz.springboot bag)
Spring Boot configuration file

Spring Boot uses a global configuration file, application.properties or APPLICATION.YML, placed under the "src/main/resources" directory or/config the classpath.

Spring Boot supports not only the general properties configuration file, but also the Yaml language configuration file. YAML is a data-centric language that has object-oriented features when it comes to configuring data.

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

  • A simple example.

We also set the TOMCAT default port to 8080, and change the default access path from " / " to "" /hello , the difference between using the properties file and the Yml file is as follows.

    • Note: yml need to : add a space after "", fortunately idea well support the format of the Yml file has good code hints;
  • We can configure multiple properties on our own

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

Restart Spring Boot, enter address: Localhost:8080/hello can see the correct result:

    • Note: We did not specify the type of the attribute in the Yml file, but it was defined when it was used.

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

You can still get the right results:

    • problem: Writing a configuration file is tedious and can cause a bloated class because there are so many @Value annotations.
  • Encapsulating configuration Information

We can encapsulate the configuration information into a class, first adding a student prefix to our name and age, and then creating a new Studentproperties class to encapsulate the information and use two annotations:

    • @Component: Indicates that the current class is a Java Bean
    • @ConfigurationProperties (prefix = "student"): means to get configuration information prefixed with sutdent

So that we can use it in the controller and reboot to get the correct information:

Spring Boot Hot Deployment

In the current Spring boot project, we need a reboot to be able to get the right results after any changes have occurred, and Spring boot provides a way for hot deployment, and when any class is found to have changed, it will be loaded by the JVM class. Load the latest class into the virtual machine so that you don't need to restart and see the modified effect.

  • The procedure is also very simple, modify pom.xml can!

Let's add a dependency to the 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 a hot deployment in idea: Portal

Spring Boot uses

The above has already completed the Spring Boot Project Simple Construction, we just need to make some simple settings, write a hellocontroller can be directly run, not too simple ... Now let's take a closer look at the use of Spring Boot.

Spring Boot Support JSP

Spring Boot's default view support is the Thymeleaf template engine, but this is not familiar to us, we still want to use JSP what to do?

  • First step: Modify Pom.xml to increase 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 Two: Configure where you want to redirect the JSP files

Modify the Application.yml file to redirect our JSP files to the/web-inf/views/directory:

  • Step Three: Modify Hellocontroller

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

  • Fourth step: Create a new hello.jsp file

In the "Src/main" directory, create the WebApp, Web-inf, and Views directory, and create a hello.jsp file:

  • Fifth step: Refresh the page

Because we have deployed the thermal deployment feature, we only need to wait for the console restart information to complete before refreshing the page to see the correct effect:

    • For 404, Running a project with Spring-boot:run can be resolved by:

Integrated MyBatis
  • First step: 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 Two: Add Database link parameters

Here we will use the Student table we created earlier:

  • Step three: Create Student entity classes and studentmapper mapping classes

Create a new "Pojo" package under "Cn.wmyskxz.springboot", and then under it a Student class:

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 under which a Studentmapper mapping class is created:

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;@Mapperpublic interface StudentMapper {    @Select("SELECT * FROM student")    List<Student> findAll();}
  • Fourth Step: Writing Studentcontroller

Create a new controller package under "Cn.wmyskxz.springboot", and then under it creates a Studentcontroller:

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 */@Controllerpublic class StudentController {    @Autowired    StudentMapper studentMapper;    @RequestMapping("/listStudent")    public String listStudent(Model model) {        List<Student> students = studentMapper.findAll();        model.addAttribute("students", students);        return "listStudent";    }}

Fifth step: Writing the liststudent.jsp file

We simplify the JSP file to show only two fields of data:

<%@ 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>
  • Sixth step: Restart the server to run

Since the new dependency package is added to Pom.xml, it is not useful to restart the server automatically, we need to restart it manually, and then at address input: Localhost:8080/liststudent See the effect:

Above.

Resources:

How2j.cn-spring Boot Series Tutorials

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

Spring Boot "Quick Start"

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.