继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Maven Spring MVC不同环境配置打包

android零基础入门
关注TA
已关注
手记 288
粉丝 97
获赞 603

思路

Maven打包项目是可以通过-P 参数, 使用profile, 向build配置中传递相关的环境配置信息, 例如

  1. dev (开发)

  2. test (测试)

  3. prod (生产)

借鉴

Spring Boot默认提供了很好的多环境配置打包的方案.
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-loading-yaml

和通过配置文件的环境命名获取相应环境的配置

实践

1. 配置pom.xml的profile

如下定义env的三种参数, 设置dev为默认激活(为开发调试方便)

    <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>prod</id>            <properties>                <env>prod</env>            </properties>        </profile>    </profiles>

pom.xml中就有了变量 ${env}

2. 使用变量 ${env}

在build中使用该变量去引入不同环境的配置文件

    <build>        <finalName>xxxxxx</finalName>        <resources>            <resource>                <directory>src/main/resources</directory>                <includes>                    <include>config-${env}.properties</include>                    <include>config.properties</include>                    <include>**.xml</include>                </includes>                <filtering>true</filtering>            </resource>        </resources>        <plugins>            <plugin>                <artifactId>maven-compiler-plugin</artifactId>                <configuration>                    <source>1.7</source>                    <target>1.7</target>                    <encoding>UTF-8</encoding>                </configuration>            </plugin>        </plugins>    </build>

使用${env} 引入 src/main/resources中不同环境的配置文件

3.项目的spring.xml配置设置

所有按照上述的配置后, 在项目spring初始化引入配置文件 需要做如下设置

<context:property-placeholder     file-encoding="utf-8"    ignore-resource-not-found="true"    ignore-unresolvable="false"     location="        classpath:/config.properties,        classpath:/config-dev.properties,          classpath:/config-test.properties,        classpath:/config-prod.properties" />

ignore-resource-not-found设置为true 因为配置了按环境配置文件打包,项目启动时,只会出现启动两个properties, config.propertiesconfig-{evn}.properties, 配置的另外两个文件是查找不到.

ignore-unresolvable 设置为 false 防止出现配置缺失的问题, 及时报错

location 按如下配置路径,加载的顺序为依次的配置文件依次写顺序.
所以先加载默认的 config.properties, 该文件可以写一些公用,相同的配置参数.
config-${env}.propertis 写一些系统的参数, 比如数据库连接信息.

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP

热门评论

不管用啊,兄弟。我过滤了,但是在<content> 的时候还是把dev,test,prod的配置文件都引进来了,哪个在后面 哪个生效

查看全部评论