SpringBoot learning notes 1: basic content

Keywords: Java Spring Spring Boot

SpringBoot Basics

SpringBoot overview

SpringBoot: SpringBoot provides a way to quickly use Spring. Based on the idea that convention is better than configuration, developers do not have to switch between configuration and business logic, which greatly improves the development efficiency.

Spring disadvantages

  1. Cumbersome configuration

    Although spring's component code is lightweight, its configuration is heavyweight. At first, spring was configured with XML, and there were many XML configurations. Spring 2.5 introduces annotation based component scanning, which eliminates a large number of explicit XML configurations for the application's own components. Spring 3.0 introduces Java based configuration, which is a type safe reconfigurable configuration method that can replace XML.
    All of these configurations represent development losses. Because there is a need to switch between thinking about Spring feature configuration and solving business problems, writing configuration takes up the time to write application logic. Like all frameworks, Spring is useful, but it requires a lot of return.

  2. Dependency cumbersome

    Project dependency management is also a time-consuming and labor-consuming thing. When setting up the environment, it is necessary to analyze the coordinates of which libraries to import, as well as the coordinates of other libraries that depend on them. Once the wrong dependent version is selected, the resulting incompatibility will seriously hinder the development progress of the project.

SpringBoot features
  1. Auto configuration

    The automatic configuration of Spring Boot is a run-time (more accurately, application startup) process. Many factors are considered to determine which Spring configuration should be used and which should not be used. This process is done automatically by SpringBoot.

  2. Dependency: dependency delivery

    Start dependency is essentially a Maven Project Object Model (POM), which defines the transfer dependency on other libraries. These things together support a certain function.
    In short, start dependency is to package the coordinates with certain functions and provide some default functions.

  3. Auxiliary function

    It provides some common non functional features in large projects, such as embedded server, security, indicators, health detection, external configuration, etc.

    Note: SpringBoot provides an embedded server, which defaults to Tomcat, so web applications do not need to be packaged as war packages, but as jar packages.

Spring boot is not an enhancement to spring, but provides a way to use spring quickly.

SpringBoot quick start


Build the SpringBoot project, define the HelloController.hello() method, and return "Hello SpringBoot!".

Implementation steps
  1. Create Maven project
  2. Import SpringBoot dependency
  3. Define Controller
  4. Write boot class
  5. Start test


  <!--  SpringBoot Project needs inherited parent project-->
    <relativePath/> <!-- lookup parent from repository -->

    <!--    web Development start dependence-->



public class HelloController {

  public String hello(){
    return "hello springboot";


4. Boot class HelloApplication.java

 * Boot class: the entry to the SpringBoot project
public class HelloApplication {

  public static void main(String[] args) {

  1. SpringBoot uses jar packaging when creating projects.
  2. The boot class of SpringBoot is the project entry. You can start the project by running the main method.
  3. For projects built with SpringBoot and Spring, the business code is written in exactly the same way.
Spring boot project quick build

Select Spring Initializr

Directory structure in resources folder

  • Static: save all static resources: js/css/images, etc

    • It can be accessed directly through the browser address bar

    • Create index.html under this folder, and the page will be the default home page. That is, enter in the address field http://localhost:8080 You can directly access this page without other configurations.

    • If there are other static folders under this folder, you need to configure them in application.properties

      • spring.mvc.static-path-pattern=/static/**  Otherwise, the static files under this file cannot be referenced or accessed
  • templates: save all template pages: (the default jar package of Springboot uses embedded Tomcat, and JSP pages are not supported by default); You can use the template engine

    • #Configure template engine
                spring.mvc.view.suffix=.html(Note: fill in the suffix corresponding to your own page here. Mine is html Page)
  • application.properties

Analysis of SpringBoot start dependency principle

1) spring-boot-starter-parent



  • The version information of various technologies is defined in spring boot starter parent, and a set of optimal matching technology versions are combined.
  • In various starter s, the coordinate set required to complete this function is defined, and most of the version information comes from the parent project.
  • Our project inherits the parent. After introducing the starter, we can easily obtain the required jar package through dependency transfer, and there will be no version conflict and other problems.

SpringBoot configuration

Profile classification

SpringBoot is convention based, so many configurations have default values. However, if you want to replace the default configuration with your own configuration, you can use application.properties or application.yml(application.yaml) for configuration.

  • properties

  • yml:

    	port: 8080
    	path: /index.html
  • SpringBoot provides two types of configuration files: properties and yml/yaml

  • Default profile name: application

  • Under the same level directory, the priority is: Properties > YML > yaml


yaml file takes data as the core, which is more concise than the traditional xml method. The extension of yaml file can use. yml or. yaml.

YAML basic syntax

  • Case sensitive
  • The data value must be preceded by a space as a separator
  • Use indentation to represent hierarchical relationships
  • The Tab key is not allowed to be used during indentation, and only spaces are allowed (the number of spaces corresponding to tabs in each system may be different, resulting in hierarchy confusion)
  • The number of indented spaces is not important, as long as the elements of the same level are aligned to the left
  • #Indicates a comment

YAML data format

  • Object (map): collection of key value pairs

      name: zhangsan
    # Inline writing
    person: {name: zhangsan}
  • Array:

      - beijing
      - shanghai
    # Inline writing
    address: [beijing,shanghai]
  • Scalar: a single, non separable value

    msg1: 'hello \n world'  # Single quotation marks ignore escape characters and output as is
    msg2: "hello \n world"  # Double quotation marks identify escape characters and escape output

YAML parameter reference

name: lisi
  name: ${name} #Reference the name value defined above

Random numbers can be used in the configuration file



  1. Profile type
    • properties: same as before
    • yml/yaml: Note spaces
  2. yaml: concise, data centric
    • Basic grammar
      • Case sensitive
      • The data value must be preceded by a space as a separator
      • Use space indents to indicate hierarchical relationships, and the same indents to indicate the same level
    • data format
      • object
      • Array: use "-" to represent each element of the array
      • Pure quantity
    • Parameter reference
      • ${key}
Read configuration file contents
  1. @Value
  2. Environment
  3. @ConfigurationProperties

@Value mode

  @Value("${name}")	//Key value pair private string name@ Value("${person.name}") 	// Key value pair private string Name2@ Value("${address[0]}") 	// Array private string address1@ Value("${msg1}") 		// Single quote scalar private string MSG1@ Value("${msg2}") 		// Double quoted scalar private String msg2;

Environment mode

  @Autowired  private Environment env;    System.out.println(env.getProperty("person.name"));  System.out.println(env.getProperty("address[0]"));


@Component@ConfigurationProperties(prefix = "person")public class Person {  private String name;  private int age;	...}

Note: @ Value get Value is compared with @ ConfigurationProperties get Value

functionProperties in batch injection profileSingle designation
Loose grammarsupportI won't support it
SpELI won't support itsupport
JSR303 data verificationsupportI won't support it

Add @ ConfigurationProperties and @ Validated annotations to support the verification function. For example, @ Email,@NotBlank

@PropertySource specifies the injection profile

@PropertySource is only valid for the properties file, not yml/yaml

@PropertySource(value = {"classpath:person.properties"})

SpringBoot recommends adding components to the container: full annotation

@Configurationpublic class MyAppConfig {  //Add the return value of the method to the container. The default id of the component in the container is the method name @ bean public person() {return new person();}}

When we develop Spring Boot applications, usually the same set of programs will be installed in different environments, such as development, testing, production, etc. The database address, server port and other configurations are different. If you have to modify the configuration file every time you package, it is very troublesome. The profile function is used for dynamic configuration switching.

  1. profile configuration mode
    • Multi profile file mode
    • yml multi document mode
  2. profile activation mode
    • configuration file
    • Virtual machine parameters
    • Command line parameters

Multiple profiles file mode


Activate profiles in application.properties


yml multi document mode

---server:  port: 8082spring:  profiles: dev---server:  port: 8082spring:  profiles: dev

Virtual machine parameter activation

VM options:


Command line parameter activation

Program arguments:


profile summary

  1. profile is used to configure the dynamic switching function in different environments.
  2. profile configuration mode
    • Multiple profile file mode: multiple profiles are provided, each representing an environment.
      • Application dev.properties/yml development environment
      • application-test.properties/yml test environment
      • application-pro.properties/yml production environment
    • yml multi document mode:
      • Use in yml - separate different configurations
  3. profile activation mode
    • Configuration file: configure spring.profiles.active=dev in the configuration file
    • Virtual machine parameters: specify in VM options: - Dspring.profiles.active=dev
    • Command line parameters: java – jar xxx.jar --spring.profiles.active=dev
Internal configuration loading sequence

When the Springboot program starts, the configuration file is loaded from the following location:

  1. file:./config /: under the / config directory of the current project
  2. file:. /: the root directory of the current project
  3. classpath:/config /: the / config directory of the classpath
  4. Classpath: /: the root directory of the classpath

The loading order is the above arrangement order, and the properties of high priority configuration will take effect

External configuration loading order

External command line configuration > internal configuration

SpringBoot integrates other frameworks

Spring boot integrates JUnit
  1. Build SpringBoot project
  2. Introducing starter test dependency
  3. Writing test classes
  4. Add test related notes
    • @RunWith(SpringRunner.class)
    • @SpringBootTest(classes = startup class. class)
  5. Writing test methods

Note: the advanced version of SpringBoot uses junit5 for unit testing and can be tested without RunWith annotation. It should be 2.0 and above, at least 2.4.0.

Spring boot integrates redis
  1. Build SpringBoot project
  2. Introducing redis start dependency
  3. Configure redis related properties
  4. Inject RedisTemplate template template
  5. Write test method, test
@Autowiredprivate RedisTemplate redisTemplate;@Testpublic void setTest() {  redisTemplate.boundValueOps("name").set("tom");}@Testpublic void getTest() {  Object name = redisTemplate.boundValueOps("name").get();  System.out.println("name = " + name);}
SpringBoot integrates MyBatis
  1. Build SpringBoot project
  2. Introduce MyBatis startup dependency and add mysql driver
  3. Write DataSource and MyBatis related configuration
  4. Define tables and entity classes
  5. Write dao and mapper files / pure annotation development
  6. test

Step 2:

Add MyBatis Framework and MySQL Driver

Step 3:

# dataSourcespring:  datasource:    url: jdbc:mysql://    username: root    password: root    driver-class-name: com.mysql.cj.jdbc.Driver

Consolidate Driud data sources

1. Introducing druid dependency

2. Update profile

spring:  datasource:    url: jdbc:mysql://    username: root    password: root    driver-class-name: com.mysql.cj.jdbc.Driver    type: com.alibaba.druid.pool.DruidDataSource

druid detailed configuration

# Data source configuration spring:    datasource:        type: com.alibaba.druid.pool.DruidDataSource        driverClassName: com.mysql.cj.jdbc.Driver        druid:            # Master database data source            master:                url: jdbc:mysql://Localhost: 3306 / ry? Useunicode = true & characterencoding = utf8 & zerodatetimebehavior = converttonull & usessl = true & servertimezone = GMT% 2B8 Username: root password: root # from library data source slave: # from data source switch / default off enabled: false URL: Username: Password: # initial number of connections initialSize: 5 # minimum number of connection pools minIdle: 10 # maximum number of connection pools maxActive: 20 # configure the timeout time for obtaining connections maxWait: 60000 # configure how often to detect, Detect idle connections that need to be closed. The unit is milliseconds. Timebetween evictionrunsmillis: 60000 # configure the minimum survival time of a connection in the pool. The unit is milliseconds. minEvictableIdleTimeMillis: 300000 # configure the maximum survival time of a connection in the pool, The unit is milliseconds maxEvictableIdleTimeMillis: 900000 # configuration to detect whether the connection is valid validationquery: select 1 from dual testwhiteidle: true testonmirror: false testonreturn: false webstatfilter: enabled: true statviewservlet: Enable Led: true # sets the white list, If it is not filled in, all users are allowed to access allow: URL pattern: / Druid / * # console management user name and password login Username: ruoyi login password: 123456 filter: stat: enabled: true # slow SQL record log-slow-s ql: true                    slow-sql-millis: 1000                    merge-sql: true                wall:                    config:                        multi-statement-allow: true

Through annotation development, MyBatis does not need to be configured

Step 5

@Mapper@Repositorypublic interface UserMapper {  @Select("select * from userinfo")  List<User> findAll();}

Step 6: Test

@SpringBootTestclass SpringbootMybatisApplicationTests { @Autowired private UserMapper userMapper; @Test void findAllTest() {  List<User> list = userMapper.findAll();  System.out.println(list); }}

Xml development

@Mapper@Repositorypublic interface UserXmlMapper {    List<User> findAll();  }


<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.example.springbootmybatis.mapper.UserXmlMapper">  <select id="findAll" resultType="user">    select * from userinfo  </select></mapper>

application.yml configure MyBatis information

# mybatismybatis:  mapper-locations: classpath:mapper/*Mapper.xml  # mapper Map file path  type-aliases-package: com.example.springbootmybatis.domain# config-location:  # Specify core profile
SpringBoot JPA mode
  1. Introduce spring boot starter data JPA
  2. Configuration file print SQL statement
  3. Create Entity annotation JPA annotation
  4. Create a Repository interface to inherit JpaRepository
  5. test

Spring Data

The purpose of Spring Data project is to simplify the construction of data access technologies based on Spring framework applications, including non relational databases, relational databases, cloud data services, etc.

Consolidate SpingData JPA

JPA : ORM(Object Relational Mapping)

1. Write an entity class (Bean) to map with the data table, and configure the mapping relationship

//Use the JPA annotation to configure the mapping relationship @ Entity / / tell JPA that this is an Entity class (the class mapped to the data table) @ Table(name = "userinfo") //@Table to specify which data table corresponds to it; If omitted, the default is public class user {@ ID @ generatedvalue (strategy = generationtype. Identity) / / self incremented primary key private integer userid; @ column (name = "username", length = 50) / / this is a column corresponding to the data table private string username; @ column / / if omitted, the default column name is the attribute private String password;

2. Write a Dao interface to operate the data table corresponding to the entity class

//Inherit JpaRepository to complete database operations public interface userrepository extensions JpaRepository < user, integer > {}

3. Basic configuration

spring:  datasource:    url: jdbc:mysql:// / test? Servertimezone = GMT% 2B8 Username: root password: root driver class name: com.mysql.cj.jdbc.driver type: com.alibaba.druid.pool.druiddatasource JPA: Hibernate: # update or create data table structure DDL Auto: update # console print SQL show SQL: true

4. Testing

@Testvoid getUserTest() {  User user = userRepository.findById(1).get();  System.out.println(user);}

JPA multi table query


Take Author and book as examples


package com.example.demo;import javax.persistence.*;import java.util.List;@Entitypublic class Author {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    private int Id;    private String name;    private int age;    @OneToMany( mappedBy = "author" )//The relationship between author and book is one to many. mappedBy refers to mapping through the author field in the book table. mappedBy is generally used to set as the foreign key field of the associated table. Here, if the foreign key field in the book entity is author, it is set as author. If it is set as other fields, it is impossible to connect and query private list < book > books; public void setId(int id) {        Id = id;    }    public void setName(String name) {        this.name = name;    }    public void setAge(int age) {        this.age = age;    }    public void setBooks(List<Book> books) {        this.books = books;    }    public int getId() {        return Id;    }    public String getName()  {        return name;    }    public int getAge() {        return age;    }    public List<Book> getBooks() {        return books;    }}


package com.example.demo;import javax.persistence.*;@Entitypublic class Book {    @javax.persistence.Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    private int Id;    private String name;    private float price;    @JoinColumn    @ManyToOne(cascade = CascadeType.ALL)    //The relationship between book and author is many to one. JoinColumn is used to add foreign keys, and cascade is used to cascade. CascadeType.Remove refers to cascade deletion, which is deleted by the ancestor of the associated table, and the corresponding ancestor of the associated table will also be deleted. Here, book is the associated table through the foreign key field author (the author_id foreign key in the database) associates the author table. Author is the associated table. / / similarly, CascadeType.Persist is a cascade storage, and the other words correspond to their own meanings / / CascadType.ALL contains all cascading operations private author author; public void setid (int ID) {id = ID;} public void setname (string name) {        this.name = name;    }    public void setPrice(float price) {        this.price = price;    }    public void setAuthor(Author author) {        this.author = author;    }    public int getId() {        return Id;    }    public String getName() {        return name;    }    public float getPrice() {        return price;    }     public Author getAuthor() {        return author;    }}


package com.example.demo;import org.springframework.data.repository.CrudRepository;public interface AuthorRepository extends CrudRepository<Author,Integer> {}


package com.example.demo;import org.springframework.data.repository.CrudRepository;public interface BookRepository extends CrudRepository<Book,Integer> {}

Posted by playaz on Mon, 20 Sep 2021 16:17:28 -0700