Home  >  Article  >  Java  >  A detailed introduction to the property configuration and custom property configuration of the Spring Boot series

A detailed introduction to the property configuration and custom property configuration of the Spring Boot series

黄舟
黄舟Original
2017-07-24 14:16:271941browse

In the process of using spring boot, you can find that only a very small amount of configuration is needed in the project to complete the corresponding functions. This is due to the modular configuration in spring boot. Each Starter that is relied on in pom.xml has Default configurations are sufficient for normal function development.

If you need to modify the custom or default configuration, spring boot provides a very simple method. You only need to add and modify the corresponding configuration in application.properties. (The default configuration of application.properties will be read when spring boot starts)

1. Modify the default configuration

Example 1. When spring boot develops web applications, the default startup port of tomcat is It is 8080. If you need to modify the default port, you need to add the following record in application.properties:

server.port=8888
Restart the project and you can see the startup log: Tomcat started on port(s): 8888 (http) Start port It is 8888, and you can access http://localhost:8888 normally in the browser.

Example 2, database connection information configuration in spring boot development (here using druid of com.alibaba), add the following records in application.properties:

druid.url=jdbc:mysql://192.168.0.20:3306/test
druid.driver-class=com.mysql.jdbc.Driver
druid.username=root
druid.password=123456
druid.initial-size=1
druid.min-idle=1
druid.max-active=20
druid.test-on-borrow=true

The above two examples illustrate If you need to modify the default configuration in the starter module, you only need to add the configuration that needs to be modified in application.properties.

2. Custom property configuration

In addition to modifying the default configuration in application.properties, we can also configure custom properties here and load them in the entity bean.

1. Add custom property configuration in application.properties

com.sam.name=sam
com.sam.age=11
com.sam.desc=magical sam

2. Write Bean class and load properties

Sam class needs to add @Component annotation so that spring can This class is scanned during startup and added to the spring container.

The first one: Use the @Value() supported by spring to load

package com.sam.demo.conf;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author sam
 * @since 2017/7/15
 */
@Component
public class Sam {

    //获取application.properties的属性
    @Value("${com.sam.name}")
    private String name;

    @Value("${com.sam.age}")
    private int age;

    @Value("${com.sam.desc}")
    private String desc;
    
    //getter & setter
}

The second one: Use @ConfigurationProperties(prefix="") to set the prefix, and no annotations are needed on the properties.

package com.sam.demo.conf;

import org.springframework.stereotype.Component;

/**
 * @author sam
 * @since 2017/7/15
 */
@Component
@ConfigurationProperties(prefix = "com.sam")
public class Sam {

    private String name;

    private int age;

    private String desc;

    //getter & setter
}

3. Inject and use the Sam Bean in the controller.

package com.sam.demo.controller;

import com.sam.demo.conf.Sam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author sam
 * @since 2017/7/14
 */
@RestController
public class IndexController {

    @Autowired
    private Sam sam;

    @RequestMapping("/index")
    public String index() {
        System.out.println(sam.getName() + " " + sam.getAge() + " " + sam.getDesc());
        return "index";
    }

}
Browser access: http://localhost:8080/index, the console prints out the content of sam normally.

3. Detailed explanation of application.properties property configuration

1. Parameter reference and use of random number method

In application.properties, you can directly reference other objects through ${} The value of the attribute is as follows:
com.sam.name=sam
com.sam.age=11
com.sam.desc=${name} is ${age} years old.
If you need to obtain a random number in application.properties, you can pass ${random}, as follows:
#获取随机字符串
com.sam.randomValue=${random.value}

#获取随机字符串:${random.value}
#获取随机int:${random.int}
#获取10以内的随机数:${random.int(10)}
#获取10-20的随机数:${random.int[10,20]}
#获取随机long:${random.long}
#获取随机uuid:${random.uuid}

2. Multi-environment configuration

In actual development, there may be different environments, including development environment, test environment, and production environment. Related configurations may be different for each environment, such as database information, port configuration, local path configuration, etc.

If you need to modify application.properties every time you switch to a different environment, the operation will be very cumbersome. Multi-environment configuration is provided in spring boot, making it easy for us to switch environments.

Create three new files in the same directory as application.properties:

application-dev.properties      //开发环境的配置文件
application-test.properties     //测试环境的配置文件
application-prod.properties     //生产环境的配置文件
The above three files correspond to the configuration content of development, testing, and production respectively. The next step is how to selectively reference them. These are configured.

Add in application.properties:

spring.profiles.active=dev
#引用测试的配置文件
#spring.profiles.active=test
#引用生产的配置文件
#spring.profiles.active=prod
After adding spring.profiles.active=dev and starting the application, you will find that the configuration information of dev is referenced.
It can be seen that the above three configuration files conform to the application-{profile}.properties format, and the dev in spring.profiles.active=dev added in application.properties is exactly the profile in the above configuration file. Switching is instantaneous depending on the specific environment.

When using the command to run the jar package to start the application, you can specify the corresponding configuration.

java -jar demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev

Attachment: Configuration method and priority

这些方式优先级如下:
a. 命令行参数
b. 来自java:comp/env的JNDI属性
c. Java系统属性(System.getProperties())
d. 操作系统环境变量
e. RandomValuePropertySource配置的random.*属性值
f. jar外部的application-{profile}.properties或application.yml(带spring.profile)配置文件
g. jar内部的application-{profile}.properties或application.yml(带spring.profile)配置文件
h. jar外部的application.properties或application.yml(不带spring.profile)配置文件
i. jar内部的application.properties或application.yml(不带spring.profile)配置文件
j. @Configuration注解类上的@PropertySource
k. 通过SpringApplication.setDefaultProperties指定的默认属性

Note: Command line Parameters, the way in which the jar package specifies parameters to start the application, may be unsafe. We can set it to prohibit starting the application in this way, as follows:

springApplication.setAddCommandLineProperties(false);

package com.sam.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
//        SpringApplication.run(DemoApplication.class, args);
        SpringApplication springApplication = new SpringApplication(DemoApplication.class);
        //禁止命令行设置参数
        springApplication.setAddCommandLineProperties(false);
        springApplication.run(args);
    }
}

Additional:

In addition to supporting application.properties, the configuration in spring boot also supports the configuration method of application.yml, as follows:
Create a new application.yml instead of application.properties
server:
  port: 9999

com:
  sam:
    name: sam
    age: 11
    desc: magical sam
Note: There are spaces in the middle of port: 9999. For yml syntax, please refer to: yml configuration file usage

The above is the detailed content of A detailed introduction to the property configuration and custom property configuration of the Spring Boot series. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn