Maven Spring MVC不一样环境配置打包

思路

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

  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-yamlspring

和经过配置文件的环境命名获取相应环境的配置数据库

实践

1. 配置pom.xml的profile

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

<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}ide

2. 使用变量 ${env}

在build中使用该变量去引入不一样环境的配置文件spring-boot

<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初始化引入配置文件 须要作以下设置ui

<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, 配置的另外两个文件是查找不到.spa

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

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

相关文章
相关标签/搜索