Spring-Boot creation and configuration files


foreword

As mentioned earlier, the concept and use of Spring, the next thing to introduce is a simpler version of Spring, referred to as Spring-Boot, as mentioned earlier, Spring is used to simplify some programs in Java, and SpringBoot is used to simplify Spring's

Advantages of Spring Boot

1: Start-up dependency (you can add dependencies more conveniently when creating)
2: Built-in Tomcat container
3: Quickly deploy Jar package
4: Abandon the XML configuration method
5: Provide more monitoring frameworks to facilitate the monitoring of the system run

The difference between Spring and SpringBoot

Spring needs to import dependencies from the central warehouse, but SpringBoot does not. It integrates dependencies and only needs to be imported when creating.
SpringBoot provides WEB dependencies, so that we don't need to deploy Tomcat and other operations.
Spring Boot will start automatic assembly through the starter The function then scans and configures the required Bean objects through annotations

Spring requires XML file configuration to enable some functions. Now Spring Boot does not need XML configuration. You only need to write a configuration class (@Configuration and inherit the corresponding interface) to continue configuration

Summary: 1 Quickly add dependencies, 2 Built-in WEB container, 3 Automatic assembly

The creation and use of SpringBoot

① Download the SpringBoot Help plug-in
insert image description here
② Create a new Spring Boot project,
insert image description here
set the project type of SpringBoot , etc.
This explains the type of a War package and Jar package. The War package is generally an external format, and it is usually a Jar package if it is not external. Note
: project type Generally choose maven, the project version should correspond to the JDK
insert image description here
Import the dependencies required by SpringBoot, pay attention to the version of SpringBoot! (circled in a red box), the far right indicates the referenced dependencies, the middle indicates a check, and the leftmost is the directory Note:
red The frame column must correspond to the JDK version
insert image description here
. In the last step, click finsh to complete the creation of a SpringBoot project. Here is a reminder that if the SpringBoot project is not from a domestic source, it will take a long time to create. It is recommended to change it to a domestic source!

Change domestic source configuration

① Open the settings, add the domestic source configuration, pay attention to ensure that there is this Setting file under these two paths, it is not OK if you check it (you can search for a copy of the Setting file online) ② After selecting, all projects will use the modified configuration,
insert image description here
open After this configuration, just go through the process of configuring the domestic source above again.
insert image description here

Quickly add dependencies

Note: This quick addition is Spring's official placement of some common dependencies
1: Add plugins
insert image description here

2: Right click in pom.xml
and select Generate
insert image description here

insert image description here
insert image description here
insert image description here

The core idea of ​​SpringBoot

Convention is greater than configuration
Convention 1: All classes that need to be stored in the container must be placed in the same class as the startup class or its subdirectory. If it is placed in another directory, SpringBoot will not read it. Specifically: it must be
placed Go to the demo directory.
Agreement 2: The name of the configuration file under resources must be application, and the format supports two formats: properties and yml. (The rest of the configuration file names can be created but will not take effect)

SpringBoot directory introduction

insert image description here
It should be noted that in SpringBoot, all Java files and folders must be created under the demo folder, which is a rule

SpringBoot configuration file

SpringBoot also has configuration files. SpringBoot does not have xml configuration, but it does not mean that there are no configuration files.
For example:

  • Database connection information (including user name and password settings);
  • The startup port number of the project;
  • Information such as the calling key of the third-party system;
  • Common logs and exception logs for finding and locating problems.

Classification of Configuration Types

1: System configuration items: server.port cannot be changed, used by the framework
2; User-defined configuration items: Write whatever you want, used by developers themselves, and can be read by injection using @Value("configuration item name ")
Note: @Value("${myimage.path}") contains dollar sign + curly braces to read the content inside, otherwise the Key value is read instead of the Value value
insert image description here

insert image description here

Format of the configuration file

There are two formats of configuration files, one is .properties, and the other is .yml.
Let’s explain the difference between the two configuration files. The .properties configuration file belongs to the official configuration file of Spring and is also the default configuration file of SpringBoot . The yml configuration file is a new configuration file,

Theoretically, properties can exist together with yml in a project. When properties and yml exist together in a project, if the same configuration appears in the configuration file, for example, both properties and yml are configured "server.port", then the configuration in properties will be the main one at this time, that is, the priority of the .properties configuration file is the highest , but after the .properties file is loaded, the configuration of the .yml file will also be loaded information.
Although in theory .properties can coexist with .yml, in actual business, we usually adopt a unified configuration file format for better maintenance

Read configuration file - this method is universal

If you want to actively read the content in the configuration file in the project, you can use the @Value annotation to achieve it. The @Value annotation is read using the "${}" format, as shown in the following code
insert image description here

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class ReadYml {
    
    
	 @Value("${server.port}")
	 private String port;
	 @PostConstruct
	 public void postConstruct() {
    
    
		 System.out.println("Read YML,port:" + port);
	 }
}

properties basic syntax

Properties are configured in the form of key-value, and the key and value are connected by "=", such as but
we generally don't use this configuration, (think if it is easy to use, why use the second format), the reason It is a solid key-value pair format, which means that the attribute configuration in the same data source of spring.datasource needs to be written many times, and yml solves this problem

# 配置项⽬端⼝号 , 这个是注释
server.port=8084
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding=
utf8
spring.datasource.username=root
spring.datasource.password=root

The basic syntax of yml

yml is highly readable, simple to write, and easy to understand. Its syntax is similar to the JSON language.
yml supports more data types, it can simply express list (array), hash table, scalar and other data forms. It uses whitespace symbols for indentation and features that rely heavily on appearance, and is especially suitable for expressing or editing data structures, various configuration files, etc.
yml supports more programming languages, it can be used in Golang, PHP, Python, Ruby, JavaScript, Perl not only in Java (this is the reason why yml is really popular, because properties is the official configuration of Spring Documentation, what does the general official stand for, safe and rigid)

yml is a tree-structured configuration file. Its basic syntax is "key: value". Note that the key and value are composed of English sweat plus spaces, and the spaces cannot be omitted (if the configuration is successful, the are highlighted)
Demonstration

spring:
 datasource:
 url: jdbc:mysql://127.0.0.0:3306/dbname?characterEncoding=utf8
 username: root
 password: root

yml reads the configuration in the same way as properties, just use the @Value annotation

Precautions for yml

Strings do not need single or double quotes by default.
Single quotes escape special characters, which end up being just plain string data.
Double quotes will not escape the special characters in the string; special characters will be
used as the meaning you want to express. For example: For example, if you write a front-end statement, add single quotes to get a normal string, and add double quotes to get a front-end the code

You can also configure objects in yml, and use another annotation @ConfigurationProperties to read, generally not written in this way, understand

properties VS yml good and bad

  1. properties is a key-value type configuration file configured in the form of key=value, while yml is configured in a tree configuration similar to json format, and the yml level uses a newline indentation method Type configuration, use ":" English symbols and spaces between key and value, and spaces cannot be omitted
  2. properties is an early and default configuration file format, but its configuration has certain redundant data. Using yml can solve the problem of data redundancy very well.
  3. yml is more versatile and supports more languages, such as Java, Go, Python, etc. For cloud server development, you can use a configuration file as a common configuration file for Java and Go.
  4. yml supports more data types. yml supports Chinese, and properties have to be set in Chinese,

Read objects in yml

1: Create an object in yml

student:
  id: 1
  name: Java
  age: 18

2: Create a Bean object, create the corresponding class of the object, must have Set and Get methods

package com.example.demo.controller;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@ConfigurationProperties(prefix = "student")
@Component
public class Student {
    
    
    private int id;
    private String name;
    private int age;

    public int getId() {
    
    
        return id;
    }

    @Override
    public String toString() {
    
    
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }
}

insert image description here

3: Add the annotation ConfigurationProperties to this class, and add 5 major types of annotations
4: Then you can use
insert image description here
the result as follows
insert image description here
Annotation: @RestController
is equivalent to the combination of //@Controller and //@ResponseBody, the effect is the same as adding these two at the same time the same

code development environment

1: Local development environment
2: Test environment
3: Production environment (officially for customers)

Guess you like

Origin blog.csdn.net/qq_56454895/article/details/131147610