Springboot from entry to mastery (3)

Springboot reads the configuration file

        There are two forms of configuration files in springboot, the first is the traditional properties form, and the second is the yml format file, which is also the configuration form officially recommended by spring, with a relatively clear structure.

        Let's take a simple data source configuration to see the difference between the two configuration files:

        The properties are like this:

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

        And in the yml file is like this:

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

It is not difficult to see that the configuration in yml form is more concise and easy to understand.

But both read the same way.

1. First add the following dependencies to the pom file of the demo project:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- Support @ConfigurationProperties annotation -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

2. Create a new application.yml file under the resources source file, and configure a slightly more complex structure in it:

myProps:
  simpleProp: simplePropValue
  arrayProps:  1,2,3,4,5
  listMapProps:
    - name: abc
      value: abcValue
    - name: def
      value: defValue
  listStrProp:
    - strValue1
    - strValue2
  mapProps:
    key1: value1
    keys: value2

From the analysis of the configuration file, it can be seen that its root node is myProps,

1. His first property is simpleProp, and the value is a string;

2. The second property is arrayProps, and the value is an array containing five integers;

3. The third attribute can be understood as a list with a map and two pieces of data in it;

4. The fourth attribute is the string string contained in a list;

5. The fifth is a map set containing two key-value pairs.

After understanding the structural properties of the configuration, it is easy to write the corresponding Java entity class according to this structure.

3. Create a new configuration file entity class

package com.cfcc.prop;

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

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

@Component
@ConfigurationProperties(prefix = "myProps")
public class MyProps {
    private String simpleProp;
    private String[] arrayProps;
    private List<Map<String, String>> listMapProps;
    private List<String> listStrProp;
    private Map<String, String> mapProps;
    private String name;

    public String getName() {
        return name;
    }

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

    public String getSimpleProp() {

        return simpleProp;
    }

    public void setSimpleProp(String simpleProp) {
        this.simpleProp = simpleProp;
    }

    public String[] getArrayProps() {
        return arrayProps;
    }

    public void setArrayProps(String[] arrayProps) {
        this.arrayProps = arrayProps;
    }

    public List<Map<String, String>> getListMapProps() {
        return listMapProps;
    }

    public void setListMapProps(List<Map<String, String>> listMapProps) {
        this.listMapProps = listMapProps;
    }

    public List<String> getListStrProp() {
        return listStrProp;
    }

    public void setListStrProp(List<String> listStrProp) {
        this.listStrProp = listStrProp;
    }

    public Map<String, String> getMapProps() {
        return mapProps;
    }

    public void setMapProps(Map<String, String> mapProps) {
        this.mapProps = mapProps;
    }
}
@Component gives the entity class to the spring container for management

@ConfigurationProperties(prefix = "myProps") reads all configurations starting with myProps.

4. Create a new controller to read the properties configured above.

package com.cfcc.controller;

import com.cfcc.prop.JdbcTest;
import com.cfcc.prop.MyProps;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/read")
public class UserController {

    @Autowired
    private MyProps myProps;
    @Autowired
    private ObjectMapper mapper;

    @RequestMapping("/yml")
    public String ymlTest() throws JsonProcessingException {
        System.out.println("simpleProp:"+myProps.getSimpleProp());
        System.out.println("arrayProps:"+mapper.writeValueAsString(myProps.getArrayProps()));
        System.out.println("listMapProps:"+mapper.writeValueAsString(myProps.getListMapProps()));
        System.out.println("listStrProp:"+mapper.writeValueAsString(myProps.getListStrProp()));
        System.out.println("mapProps:"+mapper.writeValueAsString(myProps.getMapProps()));
        return " read yml";
    }
}

Enter localhost:8080/read/yml in the browser's address bar

The console will output the corresponding value. Here, ObjectMapper is used to convert some of the objects into strings for output, which is convenient for viewing.


In the development process of the project, we not only need to read the content in the application configuration file, but sometimes we also define some configuration files ourselves, so how should we read it?

5. Read the custom configuration file

Create a new config folder under resources, create a new test.properties file below, and add the following configuration:

com.jxc.name=kevin
com.jxc.age=23
com.jxc.addr=chengdu
com.jxc.desc=${com.jxc.name}${com.jxc.age} lives in ${com.jxc.addr}

# random string
com.didispace.blog.value=${random.value}
# random int
com.didispace.blog.number=${random.int}
# random long
com.didispace.blog.bignumber=${random.long}
# random number within 10
com.didispace.blog.test1=${random.int(10)}
# Random numbers from 10-20
com.didispace.blog.test2=${random.int[10,20]}

The properties in the current configuration can be introduced into the configuration file using ${property name}. random is an object defined by the system and can be called directly.

6. Define the configuration class that reads the configuration file.

package com.cfcc;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

/**
 * Load the properties configuration file, which can be obtained in the method
 * kevin.properties file does not exist, verify ignoreResourceNotFound property
 * Add encoding = "utf-8" attribute to prevent Chinese garbled characters, not uppercase "UTF-8"
 */
@Configuration
@PropertySource( value = {"classpath:/config/test.properties","classpath:/config/kevin.properties"},ignoreResourceNotFound = true, encoding = "utf-8")
public class PropertiesConfig {
    // PropertySourcesPlaceholderConfigurer this bean,
    // This bean is mainly used to resolve ${…} placeholders used in @value.
    // If you don't use the ${...} placeholder, you can leave out this bean.
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){
        return new PropertySourcesPlaceholderConfigurer();
    }
}

7. Read configuration

The @PropertySource annotation is used here, and the path to the configuration file we defined is added to the annotation. The following bean is mainly to enable us to use the @Value annotation to read the configuration.

Inject in the controller

    @Autowired
    private Environment environment;
    @Value("${com.jxc.age}")
    private String age;

The Environment object is used to read the above-defined properties, and @Value is an annotation of the read configuration file encapsulated in spring.

@RequestMapping("/prop")
    public String propTest(){
        //Test loading properties file
        System.out.println("name:"+environment.getProperty("com.jxc.name"));
        System.out.println("age:"+age);
        System.out.println("addr:"+environment.getProperty("com.jxc.addr"));
        System.out.println("描述:"+environment.getProperty("com.jxc.desc"));

        System.out.println("random number: ");
        System.out.println("Random string: "+environment.getProperty("com.didispace.blog.value"));//32 bits
        System.out.println("随机int:"+environment.getProperty("com.didispace.blog.number"));
        System.out.println("随机long:"+environment.getProperty("com.didispace.blog.bignumber"));
        System.out.println("Random number within 10:"+environment.getProperty("com.didispace.blog.test1"));
        System.out.println("Random number of 10-20:"+environment.getProperty("com.didispace.blog.test2"));
        return "read properties";
    }

Similarly, enter localhost:8080/read/prop in the browser, and the console will output the corresponding information.

8. Multi-environment configuration file reading

In our system development, a set of programs needs to adapt to multiple application environments, such as development, testing, production, etc. The configuration of each environment is different. If you modify the configuration every time, it will become Quite cumbersome. A set of configurations that support multiple environments are provided in springboot.

In Spring Boot, the multi-environment configuration file name needs to meet the format of application-{profile}.properties, where {profile} corresponds to your environment identifier, for example:
application-dev.properties: development environment
application-test.properties: test environment
application -prod.properties:
As for which specific configuration file will be loaded in the production environment, it needs to be set through the spring.profiles.active property in the application.properties file, and its value corresponds to the {profile} value.


Let's test this multi-environment configuration:

First create a new application-dev.yml under resources

Add the following configuration:

jdbcTest:
  name: mysql

Create a new application-test.yml

Add the following configuration:

jdbcTest:
  name: oracle
The properties of the two configurations are the same, but the values ​​are different. To read the configuration, you need to add this configuration to application.yml.
spring:
  #Configuration file selection for multiple environments
  profiles:
        active: dev

Create a new JcbcTest configuration class:

package com.cfcc.prop;

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

@Component
@ConfigurationProperties(prefix = "jdbcTest")
public class JdbcTest {
    private String name;

    public String getName() {
        return name;
    }

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

Inject this class into the controller and create a new method to read it.

@Autowired
    private JdbcTest jdbcTest;
@RequestMapping("/more")
    public String getMoreEnv(){
        System.out.println("Multiple environment configuration:"+jdbcTest.getName());
        return "env";
    }

Enter localhost:8080/read/more in the browser, and the console will output mysql.

Modify the active value in the modification configuration file to test, and the oracle will be output.





Guess you like

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