SpringBoot 02 notes - SpringBoot configuration yml

Learn about bootstrapping to quickly create applications
Reference code: E:\Javawinner\fastspringboot
1. Select spring initializr - > next - > set group and java version – > next to add dependency


Various annotations

@RestController Equivalent to@Controller @ResponseBody
@RequestMapping("/hello") 
@RequestMapping(value="/hello",method= RequestMethod.GET)
@GetMapping("/hello") 
@PostMapping("/hello")
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
/*@Controller
@ResponseBody*/
@RestController
public class TestConntroller {
    /*@RequestMapping("/hello")*/
    /*@RequestMapping(value="/hello",method= RequestMethod.GET)*/
    @GetMapping("/hello") /*@PostMapping("/hello")*/
    public String Hello(){
        return "hello litaotao";
    }
}

Learn the syntax of global configuration and yaml

Global profile: application.properties     applicaion.yaml

Profile role
 modify sringboot Default values for auto configuration

1. Port number change
propertities
server.port=8081
yaml
Indent configuration files for data centric writing
server:
port: 8080
Json
{server:{port:8080}}
xml

8080

yaml basic syntax

1.Use indents to indicate hierarchical relationships
2.Spaces cannot be used when indenting tab build
3.When indenting, the number of spaces is not important, as long as the same level is aligned
4.Case sensitive

Three data structures are supported
Verification learning:

https://www.sogou.com/link?url=DSOYnZeCC_qXfWCbj5_yadPPLVUEe2k8A_8_SqV1PT8Xk8QlPvIGypUAxTqdiWFi

1.Common common values: single value, non separable value
  Key: v  key:Space v
  Name:  ""Zhang San"   
Extension: single and double quotation marks propertities No difference
yaml:Double quotation mark\n No escape of characters;Single quotation marks do string escape
2.Objects: key value pairs
 The number of spaces does not affect sibling alignment
girl:
  name: Wang Wu
  age: 20
 Also support one line
boy:  [name: zhaoliu,age: 18]
3.Array: a set of values arranged in order
 Array type requires-
Grade 1:
 - 1 class
 - 2 class
 - 3 class

Springboot gets the value of the configuration file and the setting of the configuration file encoding file

@ConfigurationProperties(prefix ="student")

Function: map the value in our configuration file to our entity class
prefix It is the top label in the configuration file, that is, where we need to bind the data
@componet:Is to put data into spring In container
 use@ConfigurationProperties This annotation needs to add dependencies
(spring.io-->project-->learn-->learn-->2.3.2reference doc-->configuration metadata-->
3generationg your own)
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

Student entity class

package com.zr.litaotao.fastspringboot.entity;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
@ConfigurationProperties(prefix ="student")
/*The prefix is the value in the configuration file*/
public class Student {
   /* @Value("${student.name}")*/
    private String name;
   /* @Value("#{10*2}")*/
    private Integer age;
   /* @Value("true")*/
    private Boolean sex;
    private Date brth;
    private Book book;
    private Map<String,Object> maps;
    private List<Object> lists;

    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;
    }

    public Boolean getSex() {
        return sex;
    }

    public void setSex(Boolean sex) {
        this.sex = sex;
    }

    public Date getBrth() {
        return brth;
    }

    public void setBrth(Date brth) {
        this.brth = brth;
    }

    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    public Map<String, Object> getMaps() {
        return maps;
    }

    public void setMaps(Map<String, Object> maps) {
        this.maps = maps;
    }

    public List<Object> getLists() {
        return lists;
    }

    public void setLists(List<Object> lists) {
        this.lists = lists;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex=" + sex +
                ", brth=" + brth +
                ", book=" + book +
                ", maps=" + maps +
                ", lists=" + lists +
                '}';
    }
}

Book

package com.zr.litaotao.fastspringboot.entity;

public class Book {
    private String bookname;
    private String auth;

    public String getBookname() {
        return bookname;
    }

    public void setBookname(String bookname) {
        this.bookname = bookname;
    }

    public String getAuth() {
        return auth;
    }

    public void setAuth(String auth) {
        this.auth = auth;
    }

    @Override
    public String toString() {
        return "Book{" +
                "bookname='" + bookname + '\'' +
                ", auth='" + auth + '\'' +
                '}';
    }
}

Yaml

server:
  port: 8080
student:
  name: Zhang San
  age: 20
  sex: true
  brth: 1998/07/18
  book:
    bookName: "Andersen's Fairy Tales"
    auth: "Andersen"
  maps: {k1: v1,k2: v2}
  lists:
    - Li Si
    - Wang Wu

FastspringbootApplicationTests junit test

package com.zr.litaotao.fastspringboot;
import com.zr.litaotao.fastspringboot.entity.Student;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)//Start the underlying spring junit test
@SpringBootTest
class FastspringbootApplicationTests {
    @Autowired
    Student student;

    @Test
    void contextLoads() {
        System.out.println(student);
    }

}

Test results:

Make clear the difference between @ ConfigurationProperties and @ Vaule (read the value in the configuration file)

1.Functional differences:
An attribute value that supports batch injection into the file, and@Vaule Need one by one
2.The difference between loose syntax:
@ConfigurationProperties Support, for example, in entity classes studentName,yml Medium is student.student-name;and@Value Loose syntax is not supported
3.springEL Differences between expressions:
@ConfigurationProperties I won't support it EL expression
4.JSR303 Differences between data verification:
@ConfigurationProperties Support data verification @Validated  @NotEmpty 
and@Value I won't support it

5.Complex type encapsulation
@ConfigurationProperties support

@PropertyResource @importResource @Bean and placeholder
@PropertyResource

@PropertyResource: specifies where to read the configuration file

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

@ImportResource
@ImportResource: import the spring configuration file to make the contents in the configuration file take effect

@ImportResource(locations ={"classpath:Student-bean.xml"})

Let spring XML validation

Equivalent to: Java config @ configuration and @ Bean

Test:

@Bean

Create a bean
 amount to: java-config  @Configuration and@Bean

placeholder

1.If the previous content is used later
${entry.attr:defoultValue}:Reference the previous attribute in the configuration file. If the attribute cannot be found, the default value is displayed

Loading sequence and location of multiple files

Multi file configuration

Multi file configuration: springboot In order to adapt to the changes of development environment or production environment, it is specially built profile Multi file configuration by ordering meals
 Format: application-profile Name of the environment.properties,application-profile.yml

Spring boot provides several activation configurations
Reference code e: \ javawinner \ profile springboot
1. Command line
Packaging operation

2. Configuration file
In application Write spring in properties profiles. active=dev
spring.profiles.active = environment name

server.port=8083
spring.profiles.active=dev

3. Method of JVM parameters
-Dspring.profiles.active=prod
-Dspring.profiles.active environment name

Yml document block
- in yml - three - represent a code block

Loading sequence and location

SpringBoot Provide the path to store the configuration file
1.In the current directory config Subdirectory
2.current directory
3.classpath Lower config Subdirectory
4.classpath Root directory of

If multiple configuration files are stored in different paths, multiple configuration files will be merged, but if there are duplicate configurations, they will be overwritten according to priority (overwriting instead of not executing). This category is sorted by priority (the configuration with high position in the list will overwrite the configuration with low position)

Auto configuration essence
springboot boot will load a large number of auto configuration classes
First, we need to see whether the integration component has an automatic configuration class written by springboot by default
When adding components to the automatic configuration class in the container, some properties will be obtained from the properpies class. We can specify the values of these properties in the configuration file

XxxautoConfiguration: auto configuration class
xxxPropertites: assign values to the encapsulation file

@Conditional and automatic profile reporting
@Conditional
@Conditional: spring annotation, which represents conditional annotation. When the condition is true, it returns true, which means that the component can be used, otherwise it cannot be used

Judge whether it can really match and return trueorfalse

Spring boot encapsulates a large number of conditional annotations
@ConditionalOnJava: whether the java version of the system meets the requirements

Automatic profile report log
Log: view which reports are automatically configured
Set it in the configuration file and turn on the debug mode. There are two situations when debug= true
1.positive matches: positive matches represent available
2.Negative matches: means that it cannot be used

Tags: Java Spring Boot xml

Posted by chetan1 on Wed, 25 May 2022 20:10:47 +0300