在 IntelliJ 里通过指定 application.properties 来启动 SpringBoot 项目

发表于 2020-06-10 16:14:56
阅读 226

介绍

介绍

我们今天来学习一下如何在 IntelliJ 里通过指定 application.properties 来启动 SpringBoot 项目

教程

建立多个 application.properties 配置文件

文件名格式

application-[name].properties

bdd5fc0664889a51.jpg

设置默认配置文件

pom.xml

在pom.xml的project节点里添加如下设置,这个设置建立了一个内部变量@env@表示默认配置文件

<profiles>
    <profile>
        <id>idea</id>
        <properties>
            <env>idea</env>
        </properties>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
    </profile>
    <profile>
        <id>develop</id>
        <properties>
            <env>develop</env>
        </properties>
    </profile>
    <profile>
        <id>product</id>
        <properties>
            <env>product</env>
        </properties>
    </profile>
</profiles>

在pom.xml的build节点里添加如下设置,第一段表示默认不用包含任何一个properties文件,第二段表示包含application.properties和application-${env}.properties两个文件即可

<resources>
    <resource>
        <directory>src/main/resources</directory>
        <excludes>
            <exclude>application*.properties</exclude>
        </excludes>
    </resource>
    <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
        <includes>
            <include>application.properties</include>
            <include>application-${env}.properties</include>
        </includes>
    </resource>
</resources>

application.properties

在application.properties里通过spring.profiles.active设置默认配置文件

spring.profiles.active=@env@

编译项目

现在编译项目的时候,就会自动加载 application-idea.properties 配置文件了

通过启动器设置

除了在 application.properties 里设置,还可以在启动器里通过指定 --spring.profiles.active 动态设置

12c1bd680f4535a1.jpg

通过命令行设置

开发阶段可以通过上面的方法设置,那么自动打包的时候呢?在使用mvn打包的时候可以通过指定 -P 设置

mvn clean package -Pidea -Dmaven.test.skip=true