百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程网 > 正文

IntelliJ IDEA 结合 maven通过profile实现多环境

yuyutoo 2024-10-16 15:47 13 浏览 0 评论

为什么需要多环境

在it项目开发过程中,会有开发、测试、生产等多套环境, 所以一般在项目中使用配置文件来区分环境变量参数,比如:开发数据库服务器Ip:192.168.1.33,生产服务器Ip是:biz_dbserver001,测试服务器上的数据库是:test_dbserver001, 不同的环境参数也是不同的,如果我们在系统开发的时候不考虑多环境管理的话,等我们从开发迁移到测试的时候,需要改动的参数会随着系统规模的增大而变得多起来, 如果漏掉任何一个参数,都会造成系统运行出来的结果不正确,或者系统不能正常工作等问题。 因此会有多环境管理,通过把系统一些参数抽象出来,然后定义多个环境参数文件, 文件定义环境特有的一些数据值。 然后在打包过程中,使用目标环境变量参数替换预定义的系统参数。 打包后,直接部署到目标环境即可保证正确运行。减少了脑力、人力工作。


在c/c++语言开发的系统中,有些参数是通过环境变量获取env,window上是注册表,有些是通过ini、conf、etc、yaml文件通过在安装过程中,把参数值写入到env或者window的注册表中,以后每次启动的时候,首先把参数都读出来,放在内存里,方便在程序运行过程中直接拿到期望的参数值。

在java系统开发中,一般都是通过配置文件properties、yaml、json文件获取。比如在springmvc项目中,一般都是application.properties、xml等配置文件。

java打包工具

像是c/c++使用make解决依赖和编译程序,java一开始使用的是自己的打包工具,从一开始的java命令,到后来的ant、maven、gradle,一点点进步。 启动本文主要介绍的是maven,其他就不细说了。

maven最核心的改进就在于提出仓库这个概念。我可以把所有依赖的包,都放到仓库里去,在我的工程管理文件里,标明我需要什么什么包,什么什么版本。在构建的时候,maven就自动帮我把这些包打到我的包里来了。我们再也不用操心着自己去管理几十上百个jar文件了。

maven使用如下:

C:\home\apache-maven-3.5.3\bin>mvn --help

usage: mvn [options] [<goal(s)>] [<phase(s)>]

Options:
 -am,--also-make                        If project list is specified, also
                                        build projects required by the
                                        list
 -amd,--also-make-dependents            If project list is specified, also
                                        build projects that depend on
                                        projects on the list
 -B,--batch-mode                        Run in non-interactive (batch)
                                        mode (disables output color)
 -b,--builder <arg>                     The id of the build strategy to
                                        use
 -C,--strict-checksums                  Fail the build if checksums don't
                                        match
 -c,--lax-checksums                     Warn if checksums don't match
 -cpu,--check-plugin-updates            Ineffective, only kept for
                                        backward compatibility
 -D,--define <arg>                      Define a system property
 -e,--errors                            Produce execution error messages
 -emp,--encrypt-master-password <arg>   Encrypt master security password
 -ep,--encrypt-password <arg>           Encrypt server password
 -f,--file <arg>                        Force the use of an alternate POM
                                        file (or directory with pom.xml)
 -fae,--fail-at-end                     Only fail the build afterwards;
                                        allow all non-impacted builds to
                                        continue
 -ff,--fail-fast                        Stop at first failure in
                                        reactorized builds
 -fn,--fail-never                       NEVER fail the build, regardless
                                        of project result
 -gs,--global-settings <arg>            Alternate path for the global
                                        settings file
 -gt,--global-toolchains <arg>          Alternate path for the global
                                        toolchains file
 -h,--help                              Display help information
 -l,--log-file <arg>                    Log file where all build output
                                        will go (disables output color)
 -llr,--legacy-local-repository         Use Maven 2 Legacy Local
                                        Repository behaviour, ie no use of
                                        _remote.repositories. Can also be
                                        activated by using
                                        -Dmaven.legacyLocalRepo=true
 -N,--non-recursive                     Do not recurse into sub-projects
 -npr,--no-plugin-registry              Ineffective, only kept for
                                        backward compatibility
 -npu,--no-plugin-updates               Ineffective, only kept for
                                        backward compatibility
 -nsu,--no-snapshot-updates             Suppress SNAPSHOT updates
 -o,--offline                           Work offline
 -P,--activate-profiles <arg>           Comma-delimited list of profiles
                                        to activate
 -pl,--projects <arg>                   Comma-delimited list of specified
                                        reactor projects to build instead
                                        of all projects. A project can be
                                        specified by [groupId]:artifactId
                                        or by its relative path
 -q,--quiet                             Quiet output - only show errors
 -rf,--resume-from <arg>                Resume reactor from specified
                                        project
 -s,--settings <arg>                    Alternate path for the user
                                        settings file
 -t,--toolchains <arg>                  Alternate path for the user
                                        toolchains file
 -T,--threads <arg>                     Thread count, for instance 2.0C
                                        where C is core multiplied
 -U,--update-snapshots                  Forces a check for missing
                                        releases and updated snapshots on
                                        remote repositories
 -up,--update-plugins                   Ineffective, only kept for
                                        backward compatibility
 -v,--version                           Display version information
 -V,--show-version                      Display version information
                                        WITHOUT stopping build
 -X,--debug                             Produce execution debug output

C:\home\apache-maven-3.5.3\bin>

实现方式

我们这里利用maven的profile方式实现多环境变量,maven常见的两种使用Profile的方法:占位符替换和文件复制。我们使用占位符替换方式,通过在项目顶层的pom.xml文件中定义多个profile,里面分别定义不同环境的一些参数值,在通过maven package -PenvName的时候,使用envName对应的profile里面的值替换掉工程配置文件里面的${}变量的值。

  • 3.1 profile定义

pom.xml文件里面定义多个profile,如下:

<profiles>
    <profile>
        <id>生产环境</id>
        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>
        <properties>
            <_env.name>生产环境</_env.name>
            <_datasource.url>jdbc:oracle:thin:@40.17.13.150:1521:biz</_datasource.url>
            <_datasource.username>biz_product</_datasource.username>
            <_datasource.publickey>MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIa7nwUBBMpredF5d5XmbY6RTmDbgwQWzKRvqN9AfoYIMuWbVNmEnaXImJEsVNCpG1uCj5JdoxnNhyDMDrgVT7kCAwEAAQ==</_datasource.publickey>
            <_datasource.password>PCf2UyzwD4ynCrm/NiyepRtp//iMRhTNUkPM+GiVIzwXVHJiQABk1P41+yMwj5VIYJECk45aXVjuvuXOEFshQA==</_datasource.password>

            <!-- log4j参数 begin-->
            <_log4j.path>/home/lehoon/apache-tomcat-8.0.50/temp/lehoon/logs</_log4j.path>
            <!-- log4j参数 end-->

            <!-- ehcache参数 begin-->
            <_ehcache.path>/home/lehoon/apache-tomcat-8.0.50/temp/lehoon/ehcache</_ehcache.path>
            <!-- ehcache参数 end-->

            <_redis.host>localhost</_redis.host>
            <_redis.port>6379</_redis.port>
            <_redis.password>smartweb</_redis.password>
        </properties>
    </profile>
    <profile>
        <id>测试环境</id>
        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>
        <properties>
            <_env.name>测试环境</_env.name>
            <_datasource.url>jdbc:oracle:thin:@147.3.156.134:1521:ORCL</_datasource.url>
            <_datasource.username>biz_develop_test</_datasource.username>
            <_datasource.publickey>MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIa7nwUBBMpredF5d5XmbY6RTmDbgwQWzKRvqN9AfoYIMuWbVNmEnaXImJEsVNCpG1uCj5JdoxnNhyDMDrgVT7kCAwEAAQ==</_datasource.publickey>
            <_datasource.password>PCf2UyzwD4ynCrm/NiyepRtp//iMRhTNUkPM+GiVIzwXVHJiQABk1P41+yMwj5VIYJECk45aXVjuvuXOEFshQA==</_datasource.password>

            <!-- log4j参数 begin-->
            <_log4j.path>/home/lehoon/tomcat/temp/lehoon/logs</_log4j.path>
            <!-- log4j参数 end-->
            
            <!-- ehcache参数 begin-->
            <_ehcache.path>/home/lehoon/tomcat/temp/lehoon/ehcache</_ehcache.path>
            <!-- ehcache参数 end-->

            <_redis.host>localhost</_redis.host>
            <_redis.port>6379</_redis.port>
            <_redis.password>smartweb</_redis.password>
        </properties>
    </profile>

    <profile>
        <id>开发环境</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <_env.name>开发环境</_env.name>
            <_datasource.url>jdbc:oracle:thin:@localhost:1521:ORCL</_datasource.url>
            <_datasource.username>biz_develop</_datasource.username>
            <_datasource.publickey>MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIa7nwUBBMpredF5d5XmbY6RTmDbgwQWzKRvqN9AfoYIMuWbVNmEnaXImJEsVNCpG1uCj5JdoxnNhyDMDrgVT7kCAwEAAQ==</_datasource.publickey>
            <_datasource.password>PCf2UyzwD4ynCrm/NiyepRtp//iMRhTNUkPM+GiVIzwXVHJiQABk1P41+yMwj5VIYJECk45aXVjuvuXOEFshQA==</_datasource.password>

            <!-- log4j参数 begin-->
            <_log4j.path>../temp/lehoon/logs</_log4j.path>
            <!-- log4j参数 end-->

            <!-- ehcache参数 begin-->
            <_ehcache.path>../temp/lehoon/ehcache</_ehcache.path>
            <!-- ehcache参数 end-->

            <_redis.host>localhost</_redis.host>
            <_redis.port>6379</_redis.port>
            <_redis.password>smartweb</_redis.password>
        </properties>
    </profile>
</profiles>

公共配置文件common.properties定义如下:

#============================#
#===== Database sttings =====#
#============================#

#oracle database setting
jdbc.type=oracle
jdbc.driver=oracle.jdbc.OracleDriver
jdbc.url=${_datasource.url}
jdbc.username=${_datasource.username}
jdbc.password=${_datasource.password}
jdbc.publickey=${_datasource.publickey}

#pool settings
jdbc.pool.init=5
jdbc.pool.minIdle=10
jdbc.pool.maxActive=20

#jdbc.testSql=SELECT 'x'
jdbc.testSql=SELECT 'x' FROM DUAL

#redis
redis.host=${_redis.host}
redis.port=${_redis.port}
redis.password=${_redis.password}

#============================#
#===== System settings ======#
#============================#

#\u4ea7\u54c1\u4fe1\u606f\u8bbe\u7f6e
productName=webgis
copyrightYear=2018
version=V1.2.6
envName=${_env.name}

#log file path
log.path=${_log4j.path}

#\u7ba1\u7406\u57fa\u7840\u8def\u5f84, \u9700\u540c\u6b65\u4fee\u6539\uff1aweb.xml
adminPath=/a

#\u524d\u7aef\u57fa\u7840\u8def\u5f84
frontPath=/f

#\u7f51\u7ad9URL\u540e\u7f00
urlSuffix=.html

notAllowRefreshIndex=false

user.multiAccountLogin=true

#\u5206\u9875\u914d\u7f6e
page.pageSize=10


session.sessionTimeout=3600000
session.sessionTimeoutClean=3600000

#\u7f13\u5b58\u8bbe\u7f6e
ehcache.configFile=cache/ehcache-local.xml
#ehcache.configFile=cache/ehcache-rmi.xml

通过在common.properties文件中使用${}占位符,引用profile定义的节点值,就可以在maven打包过程中使用maven profile中定义的值插入到properties文件中来。

  • 3.2 定制化profile替换

如果在我们文件中,有二次配置文件,第二层引用第一层的配置文件中的变量,我们在打包的时候不想使用maven的pforile值替换第二层配置文件的话,需要使用resource去个性化定制maven打包对资源文件的处理逻辑。 在resource中可以忽略指定类型文件、指定名称文件、引入需要处理的文件等。配置如下:

<resources>
     <!-- 定制化项目各个模块下的资源配置文件及处理方式--->
			<resource>  
				<directory>../webgis-system/src/main/resources</directory>
				<includes>
					<include>**/*.xml</include>   <!-- 包含指定xml类型的文件进行处理--->
				</includes>
				<filtering>true</filtering>   <!-- 使用profile占位符替换具体的值 -->
			</resource>
			<resource>
				<directory>../webgis-PreciousMetal/src/main/resources</directory>
				<includes>
					<include>**/*.xml</include>
				</includes>
				<filtering>true</filtering>
			</resource>
			<resource>
				<directory>../webgis-common/src/main/resources</directory>
				<filtering>true</filtering>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*.xml</include>
					<include>**/*.properties</include>
				</includes>
        <excludes> <!-- 排除掉指定的文件  最终打包不会包含这些文件 -->
                    <exclude>cache/ehcache-rmi.xml</exclude>
                  <exclude>editor.html</exclude>
                  <exclude>mybatis.xml</exclude>
                  <exclude>properties/redis.properties</exclude>
                  <exclude>mybatis-generator-config.xml</exclude>
        </excludes>
				<filtering>true</filtering>
			</resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>mybatis.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
		</resources>		
<!-- 配置使用变量的配置文件-->
		<filters>
			<filter>../smartweb-common/src/main/resources/common.properties</filter>
		</filters>

配置好了后, idea 集成了maven后,点击右侧的maven栏,可以看到maven读取到了profile列表,



可以在这里切换环境,然后启动工程,就可以使用选择的环境启动、调试项目。 打包的话,直接使用build Artifacts打包即可。或者切换到控制台下使用maven package -p envName打包。


相关推荐

从零搭建高可用的 MySQL 主从复制架构(基于 Linux 实战指南)

背景在生产环境中,单点MySQL数据库容易成为性能瓶颈或单点故障源。搭建MySQL主从复制架构,可以实现读写分离、高可用,提升系统的整体稳定性与扩展性。...

国外大神成功让Nexus4吃上安卓6.0:基本可正常使用

IT之家讯10月9日消息谷歌已经于10月6日正式开启了Nexus设备Android6.0Marshmallow系统的OTA升级推送。根据之前报道的消息,老一批的Nexus手机如Nexus4/Ne...

急死!CPU被挖矿了,却找不到哪个进程

CPU起飞了最近有朋友在群里反馈,自己服务器的CPU一直处于高占用状态,但用...

甜甜的安卓5.0却让手机ROOT难度大大增加

IT之家(www.ithome.com):甜甜的安卓5.0却让手机ROOT难度大大增加对设备进行ROOT,毫无疑问,这是安卓最美丽的地方之一,不管是对于消费者来说还是开发者。Root意味着掌握更多的权...

Linux基础知识(linux基础知识点及答案)

系统目录结构/bin:命令和应用程序。/boot:这里存放的是启动Linux时使用的一些核心文件,包括一些连接文件以及镜像文件。/dev:dev是Device(设备)的缩写,该目录...

Linux 内核 6.15 发布:内存、网络、文件系统全面升级!

核心增强:性能与安全双飞升!Linux内核6.15的正式版!虽然因一个临门一脚的Bug晚了几小时,但最终还是带着一堆硬核更新闪亮登场!...

AlmaLinux 9.6 发布,新增功能亮点纷呈!

距离上一版本AlmaLinux9.5发布六个月后,基于5.14内核的AlmaLinux正式宣布其企业级Linux发行版的9.x系列第六个更新——AlmaLinux9.6(Sag...

理解Linux下的SELinux(linux seccomp)

理解Linux下的SELinux长久以来,每当遇到授权问题或者新安装的主机,我的第一反应是通过setenforce0命令禁用SELinux,来减少产生的权限问题,但是这并不是一个良好的习惯。这篇文章...

3个简单实用的网址导航网站(简洁的网站导航)

在我们使用电脑上网的时候经常会访问某些常用的网站,每一次都去通过搜索访问就比较浪费时间,添加在浏览器收藏夹不方便在其他电脑使用。找一个好用的网址导航网站就可以帮我们把所有常用的网址集合在一个页面,方便...

整点不一样的网站制作教程,教你怎么用网站模板制作网站#...

网站制作教程整点不一样的网站。不要再问我网站制作教程了,今天给你整个怎么用网站模板制作网站的教程。·1、登录账号进入后台。·2、选择模板。自助建站平台通常提供各种各样的网站模板,可以根据自己的需求和喜...

5个最好的外贸独立站模板,让你的网站更加专业

作为外贸行业从业者,一个专业且具有吸引力的网站是必不可少的。然而,建立一个专业的网站需要耗费大量的时间和精力,尤其是在设计和开发方面。为了帮助您缩短网站建设的时间和成本,以下是5个最好的外贸独立站模板...

网站建设模板 **网站建设模板:全面指南与创意构思*

网站建设模板**网站建设模板:全面指南与创意构思**随着互联网技术的迅猛发展,网站已成为企业、机构和个人展示自身形象、传递信息、实现交流的重要平台。本文将详细介绍网站建设的基本模板,并提供创意...

原地封神!一个只用套模板即可制作电子相册的网站

对于忙碌的年轻人来说,一键操作的模板意味着无需复杂的操作步骤,就能轻松制作出精美的电子相册。但是一个好的工具也是事关重要,最近发现了一款非常适合年轻人的模板---FLBOOK在线制作电子杂志平台,只需...

跨屏建站网kpfree免费网站模板2023.1.14发布更新

跨屏建站网kpfree免费网站模板2023.1.14发布更新,摒弃了之前的卡片式设计,采用了移动优先的设计原则,简化了页面设计风格,优化了代码,优化了图片质量,确保网页打开速度。砍掉了一些花哨而无用的...

响应式大型电子企业集团类网站模板源码-青柠资源网qnziyw.cn

模板信息:模板编号:10964模板编码:UTF8模板颜色:红色模板分类:科技、电子、数码设备适合行业:电子设备类企业模板介绍:本模板自带eyoucms内核,无需再下载eyou系统,原创设计、手工书写D...

取消回复欢迎 发表评论: