SpringBoot-Detailed explanation of the use of configuration files (Profile multi-environment configuration)

A lot of automatic configuration is used in Spring Boot  , but for developers, in actual projects, there will inevitably be some manual configuration by themselves. The file that carries these custom configurations is the application.properties file in the resources directory (you can also Use application.yaml file instead of application.properties file).

One, the priority of the configuration file

The application.properties configuration file in the Spring Boot project can appear in the following 4 locations:

  1. In the config folder under the project root directory .
  2.  Under the project root directory.
  3. In the config folder under the classpath .
  4.  Under the classpath .

The loading priority of these four positions is  1> 2> 3> 4 . If there are application.properties files in these 4 locations , then the priority of loading decreases from 1 to 4 , as shown in the figure below. Spring Boot will look up the configuration information according to this priority and load it into the Spring Environment  .

 Two, reference external configuration files

By default, Spring Boot looks for application.properties and loads it. If the developer does not want to use application.properties as the configuration file name, he can also define it himself. Specify the path or name of the file when packaging is started.

1. After the project is packaged, we can use command line parameters to specify the file name when starting the project.

java -jar xxx.jar --spring.config.name=filename

2. After the project is packaged, we can use the form of command line parameters to specify the location of the external configuration file when starting the project.

java -jar xxx.jar --spring.config.location=classpath:/app.properties 

3. Of course, we can also specify the folder where the external configuration is located, and the configuration file under this folder will be searched and used at startup:

java -jar xxx.jar --spring.config.location=classpath:/config/

4. We can also configure multiple paths at the same time. For example, the following example loads the external configuration file first, and if there is no external configuration file, the default configuration file in the package is used:

java -jar xxx.jar --spring.config.location=classpath:/,classpath:/config/

Three, use command line parameters to specify attributes 

In addition to configuring the attribute parameters in the configuration file, you can also specify the startup parameters by specifying the configuration file path in the second, for example, in a cluster environment, the port is specified as 8080 in the configuration file , if you want to start another 8081 Port service, you can specify the start port through --server.port . Same for other parameters

java -jar xxx.jar --server.port=8081

If a parameter with the same name already exists in the application.properties file, it will override the configuration in application.properties

Four, custom configuration properties

In projects, you often encounter certain custom configuration attributes, such as Token expiration time, scheduled task timing and other information. We can configure our own properties in application.properties .

1. We can add a simple constant configuration similar to the following in  application.properties  :

book.name=红楼梦
book.author=曹雪芹
book.price=299.9

2. The configuration attributes can also be used by mutual reference:

book.name=红楼梦
book.author=曹雪芹
book.price=299.9

# book.info 属性引用了以上三个属性
book.info=${book.name}-${book.author}-${book.price}

3. Inject configuration attribute data into class attributes.

(1).  Data can be injected into the attribute by @Value annotation in the place where it is needed . As shown below, we create a BookController and inject book.info into the bookInfo  attribute.

@RestController
public class BookController {
    @Value("${book.info}")
    private String bookInfo;

    @GetMapping("/book")
    public String boolInfo(){

        return bookInfo;
    }
}

(2). Restart the project and visit http://localhost:8081/book.

4. Inject the attribute data into the Bean.

In project development, there may be one or more configurations that will be used in multiple classes. If the same attribute is added to each class used, or each attribute is scattered in the class in the project, maintain It is relatively troublesome. We also define a configuration class separately, inject all custom attributes into this configuration class, and other used attributes can directly refer to this class.

(1), defines a named Book  of Bean , injection and configuration data to the front of the  Bean  in

@ConfigurationProperties(prefix = "book")
@Component
public class Book {

    private String name;

    private String author;

    private Double price;

    private String info;

    // 省略 getter 和 setter 方法
}

Description:

(1) The prefix attribute in @ConfigurationProperties describes the prefix of the configuration file to be loaded.

(2) Spring Boot uses a loose rule for property binding:

  • Assuming the attribute in the bean is named authorName, the attribute in the configuration file can be my.author_name, my.author-name, my.authorName or my.AUTHORNAME

(2), inject Book  into BookController

@RestController
public class BookController {

    @Resource
    private Book book;

    @GetMapping("/book")
    public String boolInfo(){

        return book.getInfo();
    }
}

(3), restart access

 Five, multi-environment configuration

Before the project is released, developers generally need to frequently switch between the development environment, test environment and production environment. At this time, a large number of configurations need to be changed frequently (such as: database, redis, mongodb, MQ, etc.). Frequent modification brings a huge workload. The configuration file name rules under different environments agreed in Spring Boot are:

  • application-{profile}.properties , the profile placeholder represents the name of the current environment.

The specific configuration steps are as follows.

1. Create a configuration file

 First  , create two configuration files in the  resources directory: application-dev.properties  and  application-prod.properties , which respectively represent the configuration in the development environment and the production environment.

#application-dev.properties
book.name=红楼梦
book.author=曹雪芹
book.price=299.9
# book.info 属性引用了以上三个属性
book.info=${book.name}-${book.author}-${book.price}



#application-prod.properties
book.name=MySQL从删库到跑路
book.author=佚名
book.price=299.9
# book.info 属性引用了以上三个属性
book.info=${book.name}-${book.author}-${book.price}

2. Configure the environment in application.properties

 (1)  Carry out the following configuration in  application.properties , it means load application-dev.properties

spring.profiles.active=dev

(2)  Carry out the following configuration in  application.properties , it means load application-prod.properties

spring.profiles.active=prod

(3) After modifying the configuration and restarting, you will visit and you will see different results

3. Configure in the code

For the configuration added in application.properties in the second step , we can also add configuration to the code to complete it. Add the following code to the main method of the startup class to replace the configuration in the second step:

@SpringBootApplication
public class Springdemo3Application {

    public static void main(String[] args) {
        SpringApplicationBuilder builder = 
                 new SpringApplicationBuilder(Springdemo3Application.class);
        builder.application().setAdditionalProfiles("dev");
        builder.run(args);
    }
}

4. Configure when the project starts

We can also dynamically specify the current environment on the command line when the project is packaged into a jar package and started:

java -jar xxx.jar --spring.profiles.active=dev

5. Specify via Maven

The three configurations mentioned above all need to modify the configuration before packaging or specify the startup parameters at startup. We can also specify the configuration through Maven, and enter the specified configuration directly when packaging.

(1) Modify the pom.xml file and add the following configuration


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
            </plugin>
        </plugins>

        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <excludes>
                    <exclude>application-dev.properties</exclude>
                    <exclude>application-prod.properties</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>false</filtering>
                <includes>
                    <include>application-${profiles.active}.properties</include>
                    <include>application.properties</include>
                </includes>
            </resource>
        </resources>

    </build>
    <profiles>
        <!--开发环境-->
        <profile>
            <id>dev</id>
            <properties>
                <profiles.active>dev</profiles.active>
                <maven.test.skip>true</maven.test.skip>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>

        <!--生产环境-->
        <profile>
            <id>prod</id>
            <properties>
                <profiles.active>prod</profiles.active>
                <maven.test.skip>true</maven.test.skip>
            </properties>
        </profile>
    </profiles>
</project>

(2) Modify the application.properties file and add the following configuration:

[email protected]@

(3) Specify the profile when packaging maven .

mvn clean package -P prod

  In this way, the packaged file will only have the file corresponding to the specified profile, as shown below:

Guess you like

Origin blog.csdn.net/small_love/article/details/111679469