Getting to know springboot for the first time [teach you how to build a springboot project] + detailed explanation of springboot logs [super detailed]

Table of contents

1. The concept of springboot

1. What is springboot?

2. Advantages of using springboot for development

What are the design principles of springboot, and what are the advantages of using springboot for development? (M)

3. Build a springboot project by hand

 ① Create a project and select dependencies

 ②Set up hot deployment (some code changes can take effect without manually re-running)

Four. springboot configuration file

1. Prerequisites

2. Two configuration files and comparison

3. springboot scans the location of the configuration file by default

4. Explain the properties file in detail

1. Grammatical rules

2. Priority

3. Custom configuration and reading of configuration information

5. Detailed explanation of springboot log

1. The concept of log (including framework)

2. The role of logs

3. Log level

4. Log creation and printing

5.lombok supplement

6.linux print log


1. The concept of springboot

1. What is springboot?

Springboot is the same as spring, both are mining constructions, but springboot is a scaffolding developed based on the spring framework, which partially optimizes the spring framework to improve the efficiency of project development.

2. Advantages of using springboot for development

What are the design principles of springboot, and what are the advantages of using springboot for development? (M)

The design principle of springboot: convention is greater than configuration

Its superior design principles make it have advantages over springframework:
① Compared with springframework, which must configure a large number of xml files to run the program, springboot has agreed many default configurations internally, and provides different configuration files to allow users to customize configuration items

②The configuration paths of many third-party frameworks (mainly including the configuration information of various frameworks) are agreed inside springboot, and various configuration information can be loaded when the project starts to realize the rapid configuration of third-party frameworks

③ springboot integrates the web container internally, no need to configure other web containers

④ springboot has more monitoring indicators, which can better understand the operation of the project

3. Build a springboot project by hand

 ① Create a project and select dependencies

 ②Set up hot deployment (some code changes can take effect without manually re-running)

 

③ Disable JMX: Because if it is not excluded, an error will be reported when the project starts. Although this error does not affect the implementation of our project, for the sake of standardization, we still add

 ④ Disable tomcat and replace it with undertow (not a mandatory option, because undertow is slightly more efficient than tomcat)

⑤ Modify the code set

Four. springboot configuration file

1. Prerequisites

Benefit from the design principles of springboot: springboot will agree (configure) many default configurations and load them when the springboot project starts, that is to say, even if the user does not perform any configuration, the springboot project will also load some configuration items by default, and at the same time Springboot provides user configuration files, allowing users to customize project configurations

2. Two configuration files and comparison

SpringBoot uses the following two global configuration files by default, and their file names are fixed.

  • application.properties
  • application.yml

Among them, application.yml is a file written in YAML language. Like application.properties, it can be automatically read when Spring Boot starts, and the default value of Spring Boot automatic configuration can be modified. Both have similar functions and can complete Spring Boot configuration (such as specifying Tomcat port, configuring mybatis, etc.), but the priority of Properties is higher than that of YAML.

3. springboot scans the location of the configuration file by default

When the springboot project is running, it will scan the following path by default, find the configuration file and customize the configuration of the project.

  • file:./config/
  • file:./config/*/
  • file:./
  • classpath:/config/
  • classpath:/
  • Note: file: refers to the root directory of the current project; classpath: refers to the classpath of the current project , namely the resources directory.

The configuration files in all the above locations will be loaded, and their priorities will decrease in order , and the smaller the sequence number, the higher the priority. Second, application.properties located in the same location takes precedence over application.yml.

Files in all locations will be loaded, and high-priority configurations will override low-priority configurations to form complementary configurations, namely:

When the same configuration content exists, the high-priority content will overwrite the low-priority content;
when different configuration content exists, the high-priority and low-priority configuration content will be combined.

4. Explain the properties file in detail

1. Grammatical rules

key=value, generally value without double quotes or single quotes

2. Priority

Depending on the location of the file, the priority of the configuration file is also different

  • file:./config/
  • file:./
  • classpath:/config/
  • classpath:/
  • Gradually decreasing priority from top to bottom

3. Custom configuration and reading of configuration information

Read the information in the configuration file through @Value

In the configuration file:

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding=utf8
spring.datasource.name=root
spring.datasource.password=abc123
 @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.name}")
    private String name;
    @Value("${spring.datasource.password}")
    private String password;

Get the customized object in the configuration class through @ConfigurationProperties(prefix = "")

In the configuration file:

# 创建自定义对象
user.username=zhangsan
user.userId=1
user.list[0]=1
user.list[1]=2
user.map.1=hhh

In class:

@ConfigurationProperties(prefix = "user")
public class User {
    private String username;
    private int userId;
    private List<Integer>list;
    private Hashtable<Integer,String>map;
    //使用init方法判断
    @PostConstruct
    public void init(){
        System.out.println(username+userId+list+map);
    }

5. Detailed explanation of springboot log

1. The concept of log (including framework)

Log information printed on the console when the program is running:
log framework 

Common log frameworks such as: log4j, logback , slf4j, jdk-logging, commons-logging... But once these frameworks involve the conversion of log frameworks in use, it is very inconvenient, so slf4j came into being, and slf4j uses For the bridging of the log framework, after the introduction of slf4j, the use of the log is relatively simple: only need to import the dependency package of a specific log framework + the dependency package of slf4j, and use the configuration classes and methods of slf4j uniformly.

2. The role of logs

  1. Find and locate problems
  2. Record user login information for big data analysis
  3. Record the operating information of the system to facilitate data recovery and locate the operator
  4. Record the execution time of the program to facilitate future optimization of the program

3. Log level

 The default log printing level of all projects is info (only info is printed, that is, the log level above it)

The log level gradually increases from top to bottom. We can modify the log printing level of the project by setting the configuration file 

# 当前项目日志的打印级别是debug
logging.level.root=debug
# 设置具体某个包下的日志打印级别
logging.level.com.ljl.springmvc_adv.controller.loginController=info

4. Log creation and printing

The usage is as follows:

package com.example.demo.Controller;

@Controller
@ResponseBody
public class LoggerController {

    // 1. 得到日志对象
    private Logger logger = LoggerFactory.getLogger(LoggerController.class);

    // 2. 打印日志
    @RequestMapping("/logger")
    public String logger(){
        logger.trace("日志级别: trace");
        logger.debug("日志级别: degue");
        logger.info("日志级别: info");
        logger.warn("日志级别: warn");
        logger.error("日志级别: error");
        return "logger";
    }
}

In the default configuration, generally only the logs of info level and above are printed

After we

@Slf4j
@Component
public class LoggerTest {
    public static void main(String[] args) {
        log.debug("这是debug级别的日志......");
        log.info("这是info级别的日志......");
        log.warn("这是warn级别的日志......");
        log.error("这是error级别的日志......");
    }
}

5.lombok supplement

Everyone thinks about a question: Why are many methods automatically generated even if they are not written after adding the @Data annotation?
Let's compare the file class before and after compilation

Our file class in the file we are writing looks like this:

@Data
@Repository//注入到容器
@ConfigurationProperties(prefix = "user")
public class User {
    private String username;
    private int userId;
    private List<Integer>list;
    private Hashtable<Integer,String>map;
    //使用init方法判断
    @PostConstruct
    public void init(){
        System.out.println(username+userId+list+map);
    }

}

After compilation:

package com.example.springboot_study.test;

import java.util.Hashtable;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Repository;

@Repository
@ConfigurationProperties(
    prefix = "user"
)
public class User {
    private String username;
    private int userId;
    private List<Integer> list;
    private Hashtable<Integer, String> map;

    @PostConstruct
    public void init() {
        System.out.println(this.username + this.userId + this.list + this.map);
    }

    public User() {
    }

    public String getUsername() {
        return this.username;
    }

    public int getUserId() {
        return this.userId;
    }

    public List<Integer> getList() {
        return this.list;
    }

    public Hashtable<Integer, String> getMap() {
        return this.map;
    }

    public void setUsername(final String username) {
        this.username = username;
    }

    public void setUserId(final int userId) {
        this.userId = userId;
    }

    public void setList(final List<Integer> list) {
        this.list = list;
    }

    public void setMap(final Hashtable<Integer, String> map) {
        this.map = map;
    }

    public boolean equals(final Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof User)) {
            return false;
        } else {
            User other = (User)o;
            if (!other.canEqual(this)) {
                return false;
            } else if (this.getUserId() != other.getUserId()) {
                return false;
            } else {
                label49: {
                    Object this$username = this.getUsername();
                    Object other$username = other.getUsername();
                    if (this$username == null) {
                        if (other$username == null) {
                            break label49;
                        }
                    } else if (this$username.equals(other$username)) {
                        break label49;
                    }

                    return false;
                }

                Object this$list = this.getList();
                Object other$list = other.getList();
                if (this$list == null) {
                    if (other$list != null) {
                        return false;
                    }
                } else if (!this$list.equals(other$list)) {
                    return false;
                }

                Object this$map = this.getMap();
                Object other$map = other.getMap();
                if (this$map == null) {
                    if (other$map != null) {
                        return false;
                    }
                } else if (!this$map.equals(other$map)) {
                    return false;
                }

                return true;
            }
        }
    }

    protected boolean canEqual(final Object other) {
        return other instanceof User;
    }

    public int hashCode() {
        int PRIME = true;
        int result = 1;
        result = result * 59 + this.getUserId();
        Object $username = this.getUsername();
        result = result * 59 + ($username == null ? 43 : $username.hashCode());
        Object $list = this.getList();
        result = result * 59 + ($list == null ? 43 : $list.hashCode());
        Object $map = this.getMap();
        result = result * 59 + ($map == null ? 43 : $map.hashCode());
        return result;
    }

    public String toString() {
        return "User(username=" + this.getUsername() + ", userId=" + this.getUserId() + ", list=" + this.getList() + ", map=" + this.getMap() + ")";
    }
}

Through these comparisons, we can draw the following conclusion: lombok will add the code of its own annotations to the class during compilation, so that the annotations will take effect.

6.linux print log

Guess you like

Origin blog.csdn.net/m0_65431718/article/details/130314758