在学习Spring Boot过程当中,搭建了Melon-Boot这个项目,同时学习到Boot与Maven结合,生成项目的打包方案。咱们也能够看到不少互联网公司内部会划分有开发、测试、发布等不一样阶段的环境,不一样的环境之间的服务配置项须要进行区分,切换。常见的环境变量有:数据库链接配置、Zookeeper Dubbox配置、URL资源配置等等。css
本文将给出与Spring Boot类似的配置方法,应用于Spring4.X当中,与Maven相结合,管理不一样环境的配置文件,经过profile实现不一样环境的打包。java
在项目pom中定义多个环境,以下所示:web
<profiles> <!--平常开发环境--> <profile> <id>test</id> <properties> <profileActive>test</profileActive> </properties> </profile> <!--预发布环境--> <profile> <id>dev</id> <properties> <profileActive>dev</profileActive> </properties> </profile> <!--线上环境--> <profile> <id>prod</id> <properties> <profileActive>prod</profileActive> <!--<package.environment>prod</package.environment>--> </properties> </profile> </profiles>
在build中定义resources资源打包规则,以下所示:数据库
<resources> <resource> <!--指定打包时,须要特殊处理的文件路径--> <directory>src/main/resources</directory> <!--处理文件时,须要对文件进行变量替换--> <filtering>true</filtering> <excludes> <!--指定打包时,不包含如下文件--> <exclude>application-dev.properties</exclude> <exclude>application-prod.properties</exclude> <exclude>application-test.properties</exclude> <exclude>application.properties</exclude> </excludes> </resource> <resource> <filtering>true</filtering> <directory>src/main/resources</directory> <includes> <include>application-${profileActive}.properties</include> <include>application.properties</include> </includes> </resource> <resource> <directory>src/main/java</directory> <filtering>false</filtering> </resource> </resources>
mvn clean
清理上次编译的target文件;mvn package
打包项目,能够看到application.properties和application-dev.properties;mvn clean package -Dmaven.test.skip=true -P dev -e
打包项目。结果和步骤3一致。src -main –bin 脚本库 –java java源代码文件 –resources 资源库,会自动复制到classes目录里 –filters 资源过滤文件 –assembly 组件的描述配置(如何打包) –config 配置文件 –webapp web应用的目录。WEB-INF、css、js等 -test –java 单元测试java源代码文件 –resources 测试须要用的资源库 –filters 测试资源过滤库 -site Site(一些文档) target LICENSE.txt Project’s license README.txt Project’s readme