This article has participated in the weekend study plan, click the link to see details: Weekend Study Plan

Accumulate over a long period, constant dripping wears away a stone 😄

preface

In SpringBoot, we often read configuration file values. What are the ways to read configuration file values? Follow the author to see!

Use @value annotations

Prepare two configuration files named application.properties and application.yml

  • properties
userproperties.name=gongj===properties
userproperties.age=11===properties
userproperties.sex=12===properties
userproperties.email=[email protected]===properties
Copy the code
  • yml
useryml:
  name: gongjie
  age: 23
  sex: 1
  email: 111@163.com
Copy the code
  • test
    @Value("${userproperties.name}")
    private String name;
    @Value("${userproperties.age}")
    private String age;
    @Value("${userproperties.sex}")
    private String sex;
    @Value("${userproperties.email}")
    private String email;

    @Value("${useryml.name}")
    private String nameyml;
    @Value("${useryml.age}")
    private String ageyml;
    @Value("${useryml.sex}")
    private String sexyml;
    @Value("${useryml.email}")
    private String emailyml;

    @Test
    public void testValue(a){
    
        System.out.println("name=" + name + ",age=" + age + ",sex=" 
        + sex + , "email" + email);
        
       System.out.println("nameyml=" + nameyml + ", ageyml =" + ageyml 
       + ", sexyml =" + sexyml + ", emailyml" + emailyml);
    }
Copy the code

Use the @configurationProperties annotation

  • properties
@Component
@ConfigurationProperties(prefix = "userproperties")
public class ReadPropertiesValue {
    private String name;
    private String age;
    private String email;
    private String sex;

    @Override
    public String toString(a) {
        return "ReadPropertiesValue{" +
                "name='" + name + '\' ' +
                ", age=" + age +
                ", email='" + email + '\' ' +
                ", sex=" + sex +
                '} ';
    }

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

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

    public void setEmail(String email) {
        this.email = email;
    }

    public void setSex(String sex) {
        this.sex = sex; }}Copy the code

Prefix: specifies the prefix of the key name in the configuration file.

Note: The @Component modifier is not used on the ReadPropertiesValue class. Is not available in the container. Need to start the class add @ EnableConfigurationProperties (ReadPropertiesValue. Class) will be registered into the container.

  • yml
@Component
@ConfigurationProperties(prefix = "useryml")
public class ReadYmlValue {
    private String name;
    private String age;
    private String email;
    private String sex;

    @Override
    public String toString(a) {
        return "ReadYmlValue{" +
                "name='" + name + '\' ' +
                ", age=" + age +
                ", email='" + email + '\' ' +
                ", sex=" + sex +
                '} ';
    }

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

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

    public void setEmail(String email) {
        this.email = email;
    }

    public void setSex(String sex) {
        this.sex = sex; }}Copy the code
  • test
    @Autowired
    ReadPropertiesValue readPropertiesValue;
    @Autowired
    ReadYmlValue readYmlValue;
    @Test
    public void readPropertiesValueTest(a){
        System.out.println(readPropertiesValue.toString());
        System.out.println(readYmlValue.toString());
    }
Copy the code

3, Use Environment

Note: This is done by dependency injection directly into the Evnironment object and then using environment.getProperty(” key name “) to read the corresponding value.

  • Coding test
@Autowired
Environment environment;

@Test
public void environmentTest(a){

    System.out.println(environment.getProperty("userproperties.name") 
    + "= =" + environment.getProperty("userproperties.age") + "= =" + 
    environment.getProperty("userproperties.sex") + "= =" + 
    environment.getProperty("userproperties.email"));

    System.out.println(environment.getProperty("useryml.name") + "= =" 
    + environment.getProperty("useryml.age") + "= =" + 
    environment.getProperty("useryml.sex") + "= =" + 
    environment.getProperty("useryml.email"));

}
Copy the code

Properties and application.yml are all read from the default configuration files. But these two files are certainly not the only ones in the company’s official development. There is usually a custom configuration file, and this is the time to specify the load configuration file.

Read from the definition configuration file

Create configValue.properties and configValue.yml configuration files

  • configValue.properties
userconfigvalueproperties.name=yuanjConfigValue
userconfigvalueproperties.age=11ConfigValue
userconfigvalueproperties.sex=12ConfigValue
userconfigvalueproperties.email=[email protected]
Copy the code
  • yml
userconfigvalueyml:
  name: yuanjconfigvalueyml
  age: 11configvalueyml
  sex: 12configvalueyml
  email: 3333@163.comconfigvalueyml
Copy the code

Use @propertysource + @Value

  • readpropertiesThe file content
@Component
@PropertySource(value = "classpath:configValue.properties")
public class ReadPropertiesByValue {

    @Value("${userconfigvalueproperties.name}")
    public String name;
    @Value("${userconfigvalueproperties.age}")
    public String age;
    @Value("${userconfigvalueproperties.sex}")
    public String sex;
    @Value("${userconfigvalueproperties.email}")
    public String email;

    @Override
    public String toString(a) {
        return "ReadPropertiesByValue{" +
                "name='" + name + '\' ' +
                ", age='" + age + '\' ' +
                ", sex='" + sex + '\' ' +
                ", email='" + email + '\' ' +
                '} '; }}Copy the code

The @propertysource annotation configures a property, value: that specifies the location of the configuration file.

  • Read the contents of the YML file
@Component
@PropertySource(value = "classpath:configValue.yml")
public class ReadYmlByValue {
    
    @Value("${userconfigvalueyml.name}")
    public String name;
    @Value("${userconfigvalueyml.age}")
    public String age;
    @Value("${userconfigvalueyml.sex}")
    public String sex;
    @Value("${userconfigvalueyml.email}")
    public String email;

    @Override
    public String toString(a) {
        return "ReadYmlByValue{" +
                "name='" + name + '\' ' +
                ", age='" + age + '\' ' +
                ", sex='" + sex + '\' ' +
                ", email='" + email + '\' ' +
                '} '; }}Copy the code
@Autowired
ReadPropertiesByValue readPropertiesByValue;

@Autowired
ReadYmlByValue readYmlByValue;

@Test
public void readPropertiesByValue(a){
    System.out.println(readPropertiesByValue.toString());
    System.out.println(readYmlByValue.toString());
}
Copy the code

Use @propertysource + @ConfigurationProperties

  • properties
@Component
@ConfigurationProperties(prefix = "userconfigvalueproperties")
@PropertySource(value = { "classpath:configValue.properties" })
public class ReadPropertiesConfigValue {
    private String name;
    private String age;
    private String email;
    private String sex;

    @Override
    public String toString(a) {
        return "ReadPropertiesConfigValue{" +
                "name='" + name + '\' ' +
                ", age='" + age + '\' ' +
                ", email='" + email + '\' ' +
                ", sex='" + sex + '\' ' +
                '} ';
    }

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

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

    public void setEmail(String email) {
        this.email = email;
    }

    public void setSex(String sex) {
        this.sex = sex; }}Copy the code
  • yml
@Component
@ConfigurationProperties(prefix = "userconfigvalueyml")
@PropertySource(value = { "classpath:configValue.yml" }, factory = CommPropertyResourceFactory.class)
public class ReadYmlConfigValue {
    private String name;
    private String age;
    private String email;
    private String sex;

    @Override
    public String toString(a) {
        return "ReadYmlConfigValue{" +
                "name='" + name + '\' ' +
                ", age='" + age + '\' ' +
                ", email='" + email + '\' ' +
                ", sex='" + sex + '\' ' +
                '} ';
    }

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

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

    public void setEmail(String email) {
        this.email = email;
    }

    public void setSex(String sex) {
        this.sex = sex; }}Copy the code

Since @propertysource is not yamL readable, we need to modify it.

import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.lang.Nullable;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

public class CommPropertyResourceFactory implements PropertySourceFactory {

@Override
publicPropertySource<? > createPropertySource(@Nullable String name, EncodedResource
        resource) throws IOException {
    String resourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename());
    if (resourceName.endsWith(".yml") || resourceName.endsWith(".yaml")) { List<org.springframework.core.env.PropertySource<? >> yamlSources =new YamlPropertySourceLoader().load(resourceName, resource.getResource());
        return yamlSources.get(0);
    } else {
        return newDefaultPropertySourceFactory() .createPropertySource(name, resource); }}}Copy the code

When you need to read YAML, add the factory parameter

@PropertySource(value = { "classpath:configValue.yml" }, factory = CommPropertyResourceFactory.class)
Copy the code
  • test
   //=========== specifies the configuration file to load
    @Autowired
    ReadPropertiesConfigValue readPropertiesConfigValue;

    @Autowired
    ReadYmlConfigValue readYmlConfigValue;

    @Test
    public void readPropertiesConfigValueTest(a){
        System.out.println(readPropertiesConfigValue.toString());
        System.out.println(readYmlConfigValue.toString());
    }
Copy the code

  • If you have any questions or errors in this article, please feel free to comment. If you find this article helpful, please like it and follow it.