springboot或Maven项目多环境(dev、test、prod)搭建

825 阅读1分钟

springboot或Maven项目多环境(dev、test、prod)搭建

简介:我们平常在开发时,通常一套程序,既用来测试,也用来开发甚至上线用的也是这一套。相信绝大部分开发人员,用的是git或者svn来管理项目的。一个项目会有多人同时进行业务开发,有时候,我们在写完代码后,提交的时候会遇到代码冲突问题,或者别的问题,如果简单的问题可以通过回滚等操作进行回滚到提交前的项目。但如果遇到比较复杂的问题,可能就需要资深人士去解决了。所以我们可以对项目进行多环境搭建,分成test(测试)、dev(预发布)、prod(正式)三个环境。这样可以实现代码隔离。出错也只是在当前环境出错,不会影响到别的环境。

1、pom的< project>下加入

<!-- 对应开发、测试、生产三种环境 -->
    <profiles>
        <!-- 开发环境 -->
        <profile>
            <id>dev</id>
            <properties>
                <env>dev</env>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <!-- 测试环境 -->
        <profile>
            <id>test</id>
            <properties>
                <env>test</env>
            </properties>
        </profile>
        <!-- 生产环境 -->
        <profile>
            <id>pro</id>
            <properties>
                <env>pro</env>
            </properties>
        </profile>
    </profiles>

2、在< project>/< build>下设置resources节点,如下:

<resources>
    <resource>
        <directory>src/main/resources</directory>
        <!-- 根据输入参数动态修改相关内容 -->
        <filtering>true</filtering>
        <!-- 资源根目录排除各环境的配置,防止在生成目录中多余其它目录 -->
        <excludes>
            <exclude>dev/**</exclude>
            <exclude>test/**</exclude>
            <exclude>pro/**</exclude>
        </excludes>
    </resource>
    <resource>
        <directory>src/main/resources/${env}</directory>
        <!-- 根据输入参数动态修改相关内容 -->
        <filtering>true</filtering>
    </resource>
</resources>

3、< project>/< build>/< plugins>打包设置中使用已编译好的classes目录

这样的话就不需要重复设置< project>/< resources>节点了

    <!-- 配置文件转移到config目录 -->
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <executions>
            <execution>
                <id>copy-resources</id>
                <phase>package</phase>
                <goals>
                    <goal>copy-resources</goal>
                </goals>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <!-- 表示把配置文件拷到和jar包同一个路径下 -->
                    <outputDirectory>
                        ${project.build.directory}/conf
                    </outputDirectory>
                    <resources>
                        <resource>
                            <directory>${project.build.directory}/classes</directory>
                            <includes>
                                <include>**/*.properties</include>
                                <include>**/*.xml</include>
                            </includes>
                        </resource>
                    </resources>
                </configuration>
            </execution>
        </executions>
    </plugin>

4、配置文件 公共的配置放在resources下,单独配置放在各自环境下,这里只测试了数据库,不同的环境配置了不同的数据库 在这里插入图片描述

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 25 天,点击查看活动详情