spring boot基于profile加载配置文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/daguanjia11/article/details/80334565

spring boot默认会将classpath根目录下的application.properties文件作为应用程序的配置文件,除此之外,还允许允许开发人员基于特定的profile来激活另一个配置文件来覆盖application.properties中的配置项,或增加新的配置项。下面来看一个例子。

首先,我希望从配置文件中加载对应的选项来给属性赋值

@ConfigurationProperties(prefix = "starter")
@Configuration
public class SystemConfig {
    private String name;
    private String version;

    // getters and setters
}

下面是application.properties文件

starter.name="spring boot starter"
starter.version="0.1.2.3.snapshot"

默认情况下,SystemConfig类的name和version会从application.properties文件中获取。

下面再加一个生产环境的配置文件,命名为application-prod.properties,很显然,它的profile就是prod。规则是:application-{profile}.properties

如果我希望启用这个配置文件的话,可以在java命令中加入-Dspring.profiles.active=prod参数

java -Dspring.profiles.active=prod -jar target/spring-boot-start-0.0.1-SNAPSHOT.jar

这种情况下,spring boot会先加载application.properties,再加载application-prod.properties,如果有重复的设置,就会覆盖。

猜你喜欢

转载自blog.csdn.net/daguanjia11/article/details/80334565