SpringBoot integration notes

1, SpringBoot quick start

1.1 rapid construction

idea development tool, jdk1 eight
1.New Project->Spring Initializr

2. Select dependent - > finish

3. Create a controller package and an IndexController class under the package

@RestController
public class IndexController {
    @RequestMapping("/hello")
    public String Hello(){
        return "study SpringBoot quick get start";
    }
}

4. Start main class

5. Access port 8080, http://localhost:8080/hello

1.2 SpringBoot dependency introduction

 <dependencies>
 		#After import, version is not required when declaring other dependencies
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.5.3</version>
        </dependency>
        
        #Spring boot starter web has integrated the spring MVC framework
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

		#The Spring Boot devtools module enables Spring Boot applications to support hot deployment and improve developers' development efficiency
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        
		#Introducing Lombok
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

1.3 use of restcontroller

1. If @ RestController is added to the class, all spring nvcurl interface mappings in the class return json format
2. @ restcontroller is provided by SpringMVC, not Springboot
3. Rest style data transmission format json format Protocol http protocol in rest microservice interface development
4.ControLer control layer annotation SpringMVCurl interface mapping returns page Jump by default. If you need to return to json format, you need ResponseBody annotation

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    @AliasFor(
        annotation = Controller.class
    )
    String value() default "";
}

1.4 SpringBoot startup mode

Mode 1

@RestController
public class IndexController {
    @RequestMapping("/hello")
    public String Hello(){
        return "study SpringBoot quick get start";
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringbootLearnApplication.class,args);
    }
}

Mode II

@Controller
@EnableAutoConfiguration
public class IndexController {
    @RequestMapping("/hello")
    @ResponseBody
    public String Hello(){
        return "study SpringBoot quick get start";
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringbootLearnApplication.class,args);
    }
}

Mode III

@Controller
@EnableAutoConfiguration
//According to the defined scanning path, assemble the classes that meet the scanning rules into the spring container
@ComponentScan("com/example/springbootlearn/controller")
public class IndexController {
    @RequestMapping("/hello")
    @ResponseBody
    public String Hello(){
        return "use ComponentScan";
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringbootLearnApplication.class,args);
    }
}

Mode 4

@RestController
public class IndexController {
    @RequestMapping("/hello")
    public String Hello(){
        return "SpringBoot start-up";
    }
}

@SpringBootApplication
public class SpringbootLearnApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootLearnApplication.class, args);
    }

}

Spring bootapplication enables automatic configuration and scans peer packages or sub packages

2, SpringBoot integrates Web development

2.1 spring boot integrates static resource access

You can create static in the src/main/resources / directory and place a picture file in that location. After starting the program, try to access http://localhost:8080/NBA_logo.jpg . If the picture can be displayed, the configuration is successful.

2.2 differences between YML and properties formats

SpringBoot supports two configuration methods, one is the properties file and the other is yml.
Using yml can reduce the repeatability of configuration files.
For example: application properties

tgxit.name=taotao
tgxit.age=18

Create a new class UserController under the controller package

@RestController
public class UserController {
    @Value("${tgxit.name}")
    private String name;
    @Value("${tgxit.age}")
    private String age;

    @RequestMapping("/getProp")
    public String getProp(){
        return name+"--"+age;
    }
}

visit http://localhost:8080/getProp , return the result value taotao – 18

Create a new application yml

#Note the yml syntax format. There is a space after the colon ':'. If no space is added, the value will not take effect
tgxit:
  name: xiaohuihui
  age: 22

Then load the main class for testing, and return the results xiaohuihui – 22

2.3 Springboot integration freemaker template engine

Introducing freemaker dependency

 <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

Write freemarkerindex ftl

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8"/>
    <title></title>
</head>
<body>
${name}
</body>
</html>

Write Controller class

@Controller
public class FreemarkerController {
    @RequestMapping("/freemarkerIndex")
    @ResponseBody
    public String freemarker(Map<String,String > result){
        result.put("name","blackhorse");
        return "freemarkerIndex";
    }
}

Start the main class for testing

2.4 condition judgment usage of freemaker template engine

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8"/>
    <title></title>
</head>
<body>
${name}
<#if sex=='0'>
    male
    <#elseif sex=='1'>
    female
        <#else>
    other
</#if>

<#if age gte 18>
    I'm an adult
    <#else>
    under age
</#if>
<#list list as user>
    ${user}
</#list>
</body>
</html>
#There are two ways to compare sizes
1.Replace with symbols > gt >= gte ; < lt  <=lte  
2.Bracketed <#if(x>y)>
@Controller
public class FreemarkerController {
    @RequestMapping("/freemarkerIndex")
    public String freemarker(Map<String,Object > result){
        result.put("name","blackhorse");
        result.put("sex","0");
        result.put("age",22);

        ArrayList<String> list=new ArrayList<>();
        list.add("tgxit");
        list.add("xiaohuihui");
        result.put("list",list);
        return "freemarkerIndex";
    }
}

Start the main class for testing

2.5 thymeleaf rendering web interface

Introduce dependency

  <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>

Add thymeleaf profile

 ##Thymeleaf template configuration
  thymeleaf:
    prefix: classpath:/templates/
    check-template-location: true
    cache: true
    suffix: .html
    encoding: UTF-8
    mode: HTML5

Writing html pages

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>UserList</title>
</head>
<body>
<table>
    full name:<span th:text="${user.userName}"></span>
    Age:<span th:text="${user.age}"></span>
</table>

</body>
</html>

Start main class test

2.6 solving the problem of thymeleaf false positives

Code optimization

@Controller
public class MyThymeleafController {
    @RequestMapping("/myThymeleaf")
    public String myThymeleaf(HttpServletRequest request, Map<String,Object> result){
        result.put("user",new UserEntity("xiaohuihui",22));
        return "myThymeleaf";
    }
}

2.7 thymeleaf loop and if judgment writing

@Controller
public class MyThymeleafController {
    @RequestMapping("/myThymeleaf")
    public String myThymeleaf(HttpServletRequest request, Map<String,Object> result){
        ArrayList<UserEntity> userEntities = new ArrayList<>();
        userEntities.add(new UserEntity("xiaoheihei1",23));
        userEntities.add(new UserEntity("xiaoheihei2",24));
        userEntities.add(new UserEntity("xiaoheihei3",25));
        result.put("userList",userEntities);
        return "myThymeleaf";
    }
}

Write html code

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>UserList</title>
</head>
<body>
<table>
    //Traverse userList
    <ul th:each="user:${userList}">
        <li th:text="${user.userName}"></li>
        <li th:text="${user.age}"></li>
    </ul>
</table>

</body>
</html>

Start main class test

Judge age, code

    <span th:if="${user.age>17}">I'm an adult</span>
    <span th:if="${user.age<18}">under age</span>

Operation results

For details, please refer to thymeleaf official website

3, Consolidated database access layer

3.1 integrate JdbcTemplate

Database table structure

CREATE TABLE 'user'(
'id' int(11) NOT NULL AUTO_INCREMENT,
'name'varchar(32)NOT NULL COMMENT 'User name',
'age' int(11) DEFAULT NULL,
PRIMARY KEY ('id')
)ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

Introduce dependency

        <!--SpringBoot integration jdbc Template frame-->
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
         <!--SpringBoot integration mysql Driver class-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>

application.yml new configuration

  datasource:
    url: jdbc:mysql://localhost:3306/jdbc
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver

**New UserService class**

@RestController
public class UserService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @RequestMapping("/insertUser")
    public String insertUser(Integer id,String userName,String pwd){
        int update=jdbcTemplate.update("insert into user values (?,?,?)",id,userName,pwd);
        return update>0?"success":"fail";
    }
}

Browser input http://localhost:8080/insertUser?id=5&userName=xiaohuihui&pwd=12356

View the database and insert the data successfully

3.2 integrating Mybatis framework query

Introduce dependency

<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
</dependency>

application.yml add configuration

  datasource:
    url: jdbc:mysql://localhost:3306/jdbc
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver

Create a new mapper package and write the UserMapper interface

@Service
public interface UserMapper {
    @Insert("insert into user values (#{id},#{name},#{age});")
    int insertUser(@Param("id") Integer id,@Param("name") String name,@Param("age") Integer age);

    @Select("select id as id ,name as name,age as age from user where id =#{id}")
    UserEntity selectUserById(@Param("id") Integer id);
}

Write UserService

@RestController
public class UserService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    UserMapper userMapper;

    @RequestMapping("/insertUser")
    public String insertUser(Integer id,String name,Integer age){
        int update=jdbcTemplate.update("insert into user values (?,?,? )",id,name,age);
        return update>0?"success":"fail";
    }

    @RequestMapping("MybatisFindById")
    public UserEntity MybatisFindById(Integer id){
        return userMapper.selectUserById(id);
    }
}

Add MapperScan scan to the main class, and the corresponding interface implementation class will be generated after compilation

@SpringBootApplication
@MapperScan("com.example.springbootlearn.mapper")
public class SpringbootLearnApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootLearnApplication.class, args);
    }

}

Start the main class for testing

3.3 integrating Mybatis insertion

     /**
      * @Description: Integrate Mybatis insert
      * @Author: At
      * @Date: 2021/8/5 20:11
      **/

    @RequestMapping("/insertUserMybatis")
    public String insertUserMybatis(Integer id,String name,Integer age){
        int insert=userMapper.insertUser(id,name,age);
        return insert>0?"success":"fail";
    }

4, Integrated hot deployment framework

4.1 integrating devtools tools

(1) Check "Build project automatically" in idea settings

(2) Press Ctrl+shift+alt + /, select Register, and select compiler.automake.allow.when.app.running

4.2 integrate Lombok to simplify code

To build an ordinary entity class, you need to manually create parameterless and parameterless construction methods, Get and Set methods, and toString methods. The code is very cumbersome.

package com.example.springbootlearn.entity;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.logging.Logger;

/**
 * @Description:
 * @Author: at
 * @Date: 2021/8/5 17:40
 */
@Data
@Slf4j
public class UserEntity {
//  private static Logger log=Logger.getLogger(String.valueOf(UserEntity.class));
    private Integer id;
    private String name;
    private Integer age;

    public UserEntity(){

    }
    public UserEntity(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

//    public Integer getId() {
//        return id;
//    }
//
//    public void setId(Integer id) {
//        this.id = id;
//    }
//
//    public String getName() {
//        return name;
//    }
//
//    public void setName(String name) {
//        this.name = name;
//    }
//
//    public Integer getAge() {
//        return age;
//    }
//
//    public void setAge(Integer age) {
//        this.age = age;
//    }
//
//    @Override
//    public String toString() {
//        return "UserEntity{" +
//                "id=" + id +
//                ", name='" + name + '\'' +
//                ", age=" + age +
//                '}';
//    }

    public static void main(String[] args) {
        UserEntity userEntity=new UserEntity();
        userEntity.setName("Zhang San");
        String username= userEntity.getName();
        System.out.println("username"+username);
        log.info("username"+username);
    }
}

5, Consolidated read profile

5.1 read configuration file with @ value annotation

1. The SpringBoot integration configuration file is divided into two categories:
application.properties
application.yml
Or
bootstrap.properties
bootstrap.yml
In contrast, the yml file format is more concise and reduces the redundancy of the configuration file.

2. Loading sequence
bootstrap. Load YML first, application Load after YML.
bootstarp.yml is used for the boot phase of the application context.
bootstrap.yml is loaded by the parent SpringApplicationContext.

3. Differences
bootstrap.yml (bootstrap.properties) is used to execute during program boot. It is used to read earlier configuration information. For example, it can be used to configure parameters used in application.yml
application.yml (application.properties) application specific configuration information can be used to configure public parameters to be used in subsequent modules.
bootstrap.yml precedes application YML loading

yml file format is the most commonly used in later development

itkt:
  name: tencent IT
  age: 22

Writing test classes

@RestController
public class MyIndexService {
    @Value("${itkt.name}")
    private String name;
    @Value("${itkt.age}")
    private String age;

    @RequestMapping("/getProp")
    public String getProp(){
        return name+"--"+age;
    }
}

visit http://localhost:8080/getProp , read application Configuration in YML

5.2 properties conversion yml format

Automatic conversion of yml and properties

5.3 @ConfigurationProperties

Introduce dependency

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
  </dependency>

ITKTEntity

@Component
@ConfigurationProperties(prefix = "itkt")
public class ITKTEntity {
    private String name;
    private String age;
    private String address;
}

MyIndexService

@RestController
public class MyIndexService {
    @Value("${itkt.name}")
    private String name;
    @Value("${itkt.age}")
    private String age;

    @Autowired
    private ITKTEntity itktEntity;

     /**
      * @Description: Use @ Value annotation
      * @Author: At
      * @Date: 2021/8/5 21:19
      **/
    @RequestMapping("/getProp")
    public String getProp(){
        return name+"--"+age;
    }

     /**
      * @Description: @ConfigurationProperties
      * @Author: At
      * @Date: 2021/8/5 21:19
      **/
    @RequestMapping("/getNameAndAgeAddress")
    public String getNameAndAgeAddress(){
        return itktEntity.toString();
    }
}

5.4 integrate different configuration files in multiple environments

application-dev.yml: development environment
application-test.yml: Test Environment
application-prd.yml: production environment
SpringBoot default read configuration file name: application

spring:
  profiles:
    active: dev #Specify environment

5.5 modify port number and context path

server:
  port: 8081 #Port number
  servlet:
    context-path: /itkt #Specify access path

Access project

6, Integrated logging framework

6.1 logback configuration log level

maven dependency

   		<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

Logback configuration

<configuration>

    <!--The main output logs in this article are console logs and system logs, sqL Exception log-->
    <!-- ‰m Output information,Zheng p log level,Thread name,%d date,%c The full name of the class-->
    <!--Console-->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d %p(%file: %line\)- %m%n</pattern><charset>UTF-8</ charset>
        </encoder>
    </appender>

    <!--system info Level log-->
    <!--<File>Log directory,None will be created automatically-->
    <!--<roLLingPolicy>Log policy, one log file per day, or more than 64 log files per day MB Time-->
    <!--encoder Log encoding and output format-->
    <appender name="fileLog"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>log/file/fileLog.1og</File>
        <rollingPolicy class="ch.qos.logback.core.rolling. TimeBasedRollingPolicy">
            <fileNamePattern>log/file/fileLog.log.%d.%i</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <!--or whenever the file size reaches 64 MB -->
                <maxFilesize>64MB</maxFilesize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <!--Format the logged event. It is responsible for two things: one is to convert the log information into a byte array, and the other is to write the byte array to the output stream.-->
        <encoder>
            <!--`To set the input format of the log-->
            <pattern>
                %d %p (%file: %line1)- %m%n
            </pattern>
            <charset>UTF-8</charset>
            <!--Set character set here-->
        </encoder>
    </appender>

    <!--sql journal-->
    <appender name="sq1File" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <File>1og/sql/sqlFi1le.log</File>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <fileNamePattern>log/sql/sq1File.log.%d.%i</fileNamePattern>
                <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFN">
                        <!--or whenever the file size reaches 64 MB -->
                     <maxFileSize>64 MB</maxFileSize>
                </timeBasedFileNamingAndTriggeringPolicy>
            </rollingPolicy>
            <!--Format the logged event. The first is to convert the log information into a byte array, and the second is to write the byte array to the output stream.-->
            <encoder>
                <!--`To set the input format of the log-->
                <pattern>
                    %d %p (%file: %line1)- %m%n
                </pattern>
                <charset>UTF-8</charset>
                <!--Set character set here-->
            </encoder>
    </appender>

    <!--error journal-->
    <appender name="errorFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>1og/error/errorFi1le.log</File>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>log/error/errorFile.%d.log.%i</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFN">
                <!--or whenever the file size reaches 64 MB -->
                <maxFileSize>64 MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <!--Format the logged event. The first is to convert the log information into a byte array, and the second is to write the byte array to the output stream.-->
        <encoder>
            <!--`To set the input format of the log-->
            <pattern>
                %d %p (%file: %line1)- %m%n
            </pattern>
            <charset>UTF-8</charset>
            <!--Set character set here-->
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="fileLog"/>
        <appender-ref ref="console"/>
        <appender-ref ref="errorFile"/>
    </root>

    <logger name="com.dolpin.mapper" level="DEBUG" additivity="false">
        <appender-ref ref="console"/>
        <appender-ref ref="sqlFile"/>
    </logger>
</configuration>

Integrate logback configuration

package com.example.springbootlearn.service;

import com.example.springbootlearn.entity.ITKTEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description:
 * @Author: at
 * @Date: 2021/8/5 20:58
 */
@RestController
@Slf4j
public class MyIndexService {
    @RequestMapping("/getLog")
    public String getLog(String name,int age){
        log.info("name:{},age:{}",name,age);
        log.debug("");
        try{

        }catch (Exception e){
            log.error("");
        }
        return name;
    }
}

6.2 integration log4j log

#Log4j.rootLogger=CONSOLE,info , error , DEBUG
log4j.rootLogger=DEBUG,error,CONSOLE,info
1og4j.appender.CONSOLE=org.apache.log4j.consoleAppender
1og4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONsOLE.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] -‰m%n
log4j.logger.info=info
log4j.appender.info=org.apache.log4j.DailyRollingFileAppender
log4j.appender.info.layout=org.apache.log4j.PatternLayout
log4j.appender.info.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [‰p] -%m%n
1og4j.appender.info.datePattern='."yyyy-MM-dd
log4j.appender.info.Threshold=info
1og4j.appender.info.append=true
1og4j-appender.info.Fi1e=D:/Project/spring.learn/code/info.log

log4j.logger.error=error
log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
1og4j.appender.error.layout=org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm}[%t][%c][%p]-%m%n
1og4j.appender.error.datePattern='."yyyy-MM-dd
log4j.appender.error.Threshold=error
1og4j.appender.error.append=true
1og4j.appender.error.File=D:/Project/spring.learn/code/error.log

1og4j.logger.DEBUG=DEBUG
1og4j.appender.DEBUG=org.apache.1og4j.DailyRollingFileAppender
log4j.appender.DEBUG.layout=org.apache.log4j.PatternLayout
log4j.appender.DEBUG.layout.ConversionPattern=%d{yyyy-MA-dd-H-mm}[%t][%c][p]-%m%n
1og4j.appender.DEBUG.datePattern= '." yyyy-MM-dd
log4j.appender.DEBUG.Threshold = DEBUG
log4j.appender.DEBUG.append=true
1og4j.appender.DEBUG.File=D:/Project/spring.learn/code/debug.log

Keywords: Spring Boot

Added by kabucek1 on Tue, 04 Jan 2022 23:16:01 +0200