springBoot教程:3.多环境配置文件

场景

在小型项目中,需要配置不同环境的配置文件。在spring boot中直接提供了运行参数的方式。

image.png

如图,如果想加载application-prod.properties的在运行的加上参数--spring.profiles.active=prod
整体的命令是

java -jar  xxx.jar --spring.profiles.active=prod # 加载application-prod.properties

但缺点就是会将所有的配置文件都打包进jar文件。如果生产环境比较敏感,那么一些账户密码就泄露了。

因此可以采用maven的方式进行打包。

<!-- 分环境打包配置文件 -->
    <profiles>
        <!-- 本地环境 -->
        <profile>
            <id>local</id>
            <build>
                <resources>
                    <resource>
                        <directory>src/main/resources/local</directory>
                    </resource>
                </resources>
            </build>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>

        <!-- 开发环境 -->
        <profile>
            <id>dev</id>
            <build>
                <resources>
                    <resource>
                        <directory>src/main/resources/dev</directory>
                    </resource>
                </resources>
            </build>
        </profile>

        <!--测试环境-->
        <profile>
            <id>tests</id>
            <build>
                <resources>
                    <resource>
                        <directory>src/main/resources/tests</directory>
                    </resource>
                </resources>
            </build>
        </profile>

        <!--线上环境-->
        <profile>
            <id>prod</id>
            <build>
                <resources>
                    <resource>
                        <directory>src/main/resources/prod</directory>
                    </resource>
                </resources>
            </build>
        </profile>
    </profiles>


    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <excludes>
                    <exclude>tests/**</exclude>
                    <exclude>prod/**</exclude>
                    <exclude>dev/**</exclude>
                    <exclude>local/**</exclude>
                </excludes>
                <filtering>true</filtering>
            </resource>
        </resources>


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

使用命令mvn clean package -Dmaven.test.skip=true -Pprod即可。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容