Detailed explanation of Spring Boot, the entry-level framework for microservice development (2)

1. Spring Boot's property configuration file

        1.1 The first form of Spring Boot's property configuration file

            Using the properties configuration file, the meaning of the following two properties is to change the access port to 8081, and add a contextPath, which can be understood as adding more layers of addresses to the address bar.

server.port=8081
server.context-path=/joyou

                Right-click DemoApplication.java ——“Run As ——“Spring Boot App Launcher

            The effect is as follows, first of all, from the log, the port has changed to 8081

            The browser access effect is as follows.

   

            Replenish:

            Properties files are the most common way to manage configuration properties. The SpringApplication class provided by Spring Boot searches and loads the application.properties file for configuration property values. The SpringApplication class searches for this file in the following locations:

1. The /config subdirectory of the current directory

2. Current directory

3. The /config package in the classpath

4.classpath

The above order also indicates the priority of the properties files contained in that location. Priority is sorted from highest to lowest.

A different property file name can be specified through the configuration property of the spring.config.name key. Additional search paths for property files can also be added via spring.config.location .

         1.2 The second form of Spring Boot's property configuration file (recommended)

                    Use yml configuration to create an application.yml file in the resources directory. code show as below.

server:
  port: 8082
  context-path: /joyou

                The effect is the same as 1.1.

                  Replenish:                   

                YAML is a better configuration file format than properties files. When there is a prefix, it is simpler to use the .yml format configuration file.

Note: When using .yml, there must be a space between the value of the property name and the colon. For example, if name: SpringBoot is correct, SpringBoot is wrong.

YAML is used very well in Ruby on Rails. YAML is a superset of JSON and a convenient format for defining hierarchical configuration data. Its basic grammar rules are as follows:

  • Case Sensitive
  • Use indentation to indicate hierarchy
  • Tab key is not allowed when indenting, only spaces are allowed.
  • The number of spaces indented does not matter, as long as elements at the same level are left aligned
  • # Indicates a comment, which is ignored by the parser from this character until the end of the line.

         1.3 Which keys are configurable in application.properties?

        Detailed configuration and instructions are given in the SpringBoot official website documentation. In Appendix A. Common application properties: http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#common-application-properties

            Incomplete statistics, this complete application properties file has 1183 lines. Among them, there are 950 attribute keys. When you see such a huge configuration, you must be intimidated. However, in actual projects, if we follow the conventions of Spring Boot, we usually do not need to specify too much configuration separately.

            1.4 About the priority of configuration

            Spring Boot provides a mechanism for priority configuration reading to help us out of this predicament.

            The configuration priority order provided by Spring Boot is more complicated. In order of priority from high to low, the specific list (from high to low) is as follows.

  •             1. Command line arguments (highest priority).
  •             2. Java system parameters obtained through System.getProperties().
  •             3. Operating system environment variables.
  •             4. JNDI properties from java:comp/env.
  •             5. The random.* properties generated by RandomValuePropertySource.
  •             6. The application-{profile}.properties or application.yml (with spring.profile) configuration file outside the jar package is specified by the spring.config.location parameter
  •             7. The application-{profile}.properties or application.yml (with spring.profile) configuration file inside the jar package
  •             8. The application.properties or application.yml (without spring.profile) configuration file outside the jar package
  •             9. The application.properties or application.yml (without spring.profile) configuration file inside the jar package
  •             10. Apply Java configuration classes, including Java classes annotated with @Configuration, and property files declared through the @PropertySource annotation.
  •             11. Default properties declared through SpringApplication.setDefaultProperties.

            If Spring Boot finds a configuration in a higher priority location, then it ignores the lower priority configuration. Below we briefly discuss these priorities. This configuration priority of Spring Boot seems complicated, but it is actually very reasonable. Command-line parameters are given the highest priority because they allow us to quickly modify configuration parameter values ​​in a test or production environment without having to repackage and deploy the application.

            By default, the SpringApplication class will convert the command line parameters starting with "--" into configuration parameters that can be used in the application. For example, "--name=Alex" will set the value of the configuration parameter "name" to "Alex".

            If you don't need this feature, you can pass SpringApplication.setAddCommandLineProperties(false)

Disable parsing of command line arguments.

2. Spring Boot custom properties

                2.1. Example of the first custom attribute  

                          In the actual development process, the program needs to read data from the configuration file (such as URL, some account passwords, etc.), so we need to customize the properties for the program to read.

                        First, define a property in yml, the format is as follows:

company: joyou
employee: 二十岁以后

                        To get a value in a Java program, the code is as follows:

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloSpringBoot {
	
	@Value("${company}")
	private String company;
	
	@Value("${employee}")
	private String employee;
	

	@RequestMapping(value="/hello" , method = RequestMethod.GET)
	public String HelloSpring(){
		
			return company+"====="+employee;
	}
}

                Using a browser to access the effect is as follows

                2.2 Calling other properties in custom properties

                        yml file configuration               

company: joyou
employee: 二十岁以后
   
All: "公司: ${company} , 员工: ${employee}"  

                    Inject All property in JAVA program

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloSpringBoot {
	
	@Value("${All}")
	private String All;
	
	
	@RequestMapping(value="/hello" , method = RequestMethod.GET)
	public String HelloSpring(){
		
			return All;
	}
}

            The effect is as shown in the figure:

            2.3 How to call one time for multiple properties

                    After reading the above example, a question will arise. If I want to call 10, 20, and 50 attribute values ​​at a time, do I need to inject 50 values ​​into the program and use 50 annotations? In order to solve this problem, Spring Boot solves it like this!

                    First of all, a girl has attributes such as height, weight, cup size, etc., we can write it like this!

Girl: 
   High: 160CM
   Weight: 80KG
   CupSize: 30A

                    Then write a class that provides Girl's properties, as well as Setter, Geter methods, and needs to use two annotations:

  •                     @Component //If there is no such annotation, it will report the error that the bean cannot be found
  •                     @ConfigurationProperties(prefix="Girl") //Find properties starting with Girl

 

                    Then inject the Gril class into the java program

package com.example.demo;

@RestController
public class HelloSpringBoot {

	@Autowired
	private Girl girl;
	
	
	@RequestMapping(value="/hello" , method = RequestMethod.GET)
	public String HelloSpring(){
		
			return girl.toString();
	}
}

                Start the program and refresh the browser, the effect is as follows:

3. Multi-environment property configuration

            3.1 Different scenarios of production and development

                    In the face of different scenarios of production and development, the values ​​of some attributes may be different. Do I need to change the attribute values ​​written in the development environment one by one in the production environment? Having said that, of course there is no need for it. We can write yml files with different requirements for attribute values ​​in two environments during development, and then call the required yml files.

                The property values ​​for the production environment Girl are as follows:

                The property values ​​for the development environment Girl are as follows:

                I just need to call different files in application.yml. The value of dev is the suffix name of the different yml files in my development and production environments ( note the naming of the two picture files above )

    Browser corresponding results

            The configuration corresponding to the second environment

        Browser corresponding results

Fill in the project directory structure so far to help understand

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324375255&siteId=291194637