Spring Boot - Custom Properties and Multi-Environment Configuration

Many people choose Spring Boot because they have abandoned the cumbersome XML configuration in the past. We only need to introduce different modules in the pom.xml file, such as spring-boot-starter-web, spring-boot-starter-redis, spring-boot- Starter-data-mongodb, etc. These modules generally have their own default configurations. We only need to configure some properties in application.properties to use each module.

We usually configure database connections, server parameters, etc. in application.properties. At the same time, we can also customize some parameters and put them in this file for the system to use.

Custom properties and loading

First, the custom properties are as follows

com.bluecoffee.space.author=bluecoffee    
com.bluecoffee.space.title=Spring Boot基础教程

Load the corresponding configuration properties through the @Value("${property name}") annotation, as shown below

    @Value("${com.bluecoffee.space.author}")
    private String blogAuthor;

    @Value("${com.bluecoffee.space.title}")
    private String blogTitle;

Verify it with unit tests

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = RestApplication.class)
public class TestProperties {

    @Value("${com.bluecoffee.space.author}")
    private String blogAuthor;

    @Value("${com.bluecoffee.space.title}")
    private String blogTitle;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Test
    public void test1(){
        try{
            Assert.assertEquals("bluecoffee", blogAuthor);
            Assert.assertEquals("Spring Boot基础教程", blogTitle);
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}

Use random numbers and custom configuration classes

Sometimes we need our parameter not to be a fixed value, but a random number (like a key). In Spring Boot's property configuration file, ${random} can be used to generate an int value, a long value or a String string to support the random value of the property.

#随机字符串
com.bluecoffee.random.str=${random.value}
#随机int
com.bluecoffee.random.number=${random.int}
#随机long
com.bluecoffee.random.bigNumber=${random.long}
#10以内的随机数
com.bluecoffee.random.test1=${random.int(10)}
#10-20的随机数
com.bluecoffee.random.test2=${random.int[20,30]}

In this configuration, we found that there is a feature, all configurations start with "com.bluecoffee.random", we can also customize a configuration class to declare, the code is as follows

@ConfigurationProperties(prefix = "com.bluecoffee.random")
public class RandomProperties {

    private String str;

    private Integer number;

    private Long bigNumber;

    private Integer test1;

    private Integer test2;

    // getter/setter方法省略
}

In the above code, @ConfigurationProperties(prefix = "com.bluecoffee.random") is used to agree to read configuration items starting with "com.bluecoffe.random", and then we don't forget to use @EnableConfigurationProperties in RestApplication.java to enable the function of reading configuration files.

@SpringBootApplication
@EnableConfigurationProperties(RandomProperties.class)
public class RestApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(RestApplication.class, args);
    }
}

Setting property values ​​from the command line

After packaging the Spring Boot application, we can use java -jar xxx.jar --server.port=9001 to set the port of the xxx.jar application to 9001 by using the --server.port property.

When running on the command line, two consecutive minus signs--is the identifier for assigning the property value in application.properties. So, the java -jar xxx.jar --server.port=9001 command is equivalent to adding the property server.port=9001 to application.properties, which we can verify by deleting the value or setting it using the command line .

Modifying property values ​​through the command line provides good convenience, but it is not safe to change the parameters of application running through the command line. You need this setting to block:

SpringApplication.setAddCommandLineProperties(false)

Multi-environment configuration

We know that in the R&D process, there are at least three environments from development-testing-launch , Distributed message component configuration, etc. If you modify the configuration during the packaging process, it is very error-prone.

For multi-environment configuration, there are a lot of project construction tools. Basically, the principle is to configure multiple configuration files for different environments, and then specify the content to be packaged through the packaging command, and then differentiate and package them. Spring Boot also supports it.

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:开发环境
application-test.properties:测试环境
application-prod.properties:生产环境

As for which specific profile will be loaded, it needs to be set through the spring.profiles.active property in the application.properties file, and its value corresponds to the {profile} value.

For example: spring.profiles.active=prod will load the content of the application-prod.properties configuration file

Next, take the configuration of different service ports in different environments as an example to test:

  • Create different configuration files application-dev.properties, application-test.properties, application-prod.properties for each environment

  • Different server.port properties are set in these three files, such as: dev environment is set to 1111, test environment is set to 2222, prod environment is set to 3333

  • Set spring.profiles.active=dev in application.properties, which means that the default is set in the dev environment

Test loading of different configurations

Execute java -jar xxx.jar, you can observe that the service port is set to 1111, that is, the default development environment (dev)
executes java -jar xxx.jar --spring.profiles.active=test, you can observe that the service port is set to 1111. Set to 2222, that is, the configuration of the test environment (test)
executes java -jar xxx.jar --spring.profiles.active=prod, it can be observed that the service port is set to 3333, that is, the configuration of the production environment (prod)
according to The above experiments can summarize the configuration ideas of multiple environments as follows:

  • Configure common content in application.properties, and set spring.profiles.active=dev, with the development environment as the default configuration
  • Configure different content for each environment in application-{profile}.properties
  • Activate the configuration of different environments through java -jar xxx.jar --spring.profiles.active={}

Guess you like

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