maven的profile

一、效果展示:想通过勾选的方式选择配置文件

 

二、需求

在开发的过程中,会用到很多的配置文件,而对于不同的运行环境需要不同的配置文件(本地开发和测试环境,以及发布上线的环境),若只有一个配置文件,每次运行环境改变了,都要去改配置文件,改来改去的很容易出错,于是就想找一个简单方便的方法修改配置文件。

 

三、实现

    1、在maven的pom.xml里面添加profile标签

直接在<project></project>这个标签里面添加

<project>
    。。。。。。。。
    <profiles>
        <profile>
            <!-- 本地开发环境 -->
            <id>dev</id>
            <properties>
            <!-- 这里的属性名是随便取的,可以在后续配置中引用 -->
                <profiles.dir>dev</profiles.dir>
            </properties>
            <!-- 是否默认 -->
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <profile>
            <!-- 测试环境 -->
            <id>test</id>
            <properties>
                <profiles.dir>test</profiles.dir>
            </properties>
        </profile>
	<profile>
            <!-- 生产环境 -->
            <id>pro</id>
            <properties>
                <profiles.dir>pro</profiles.dir>
            </properties>
        </profile>
    </profiles>
    。。。。。。。。。。
</project>

    二、添加source的路径

直接在<build></build>这个标签里面添加

</project>
    </build>
        。。。。。
        <resources>  
            <resource>  
                <filtering>true</filtering>                          
                <directory>${project.basedir}/src/main/resources</directory>  
                <excludes>
                    <exclude>test/*</exclude>
                    <exclude>pro/*</exclude>
                    <exclude>dev/*</exclude>
                </excludes>
            </resource>  
            <resource>  
                <directory>${project.basedir}/src/main/resources/${profiles.dir}</directory>  
            </resource>  
        </resources>  
        。。。。。
    </build>
</project>

说明:resources这个标签里面配置了两个资源路径,${project.basedir}这个变量是系统自己定义的(系统自定义的变量有6个),${profiles.dir}这个变量是我自己定义的,在上文的Profiles里面定义的

文件的目录结构是:resources这个文件夹一般的项目会自己创建的,如果没有就在main文件里面创建一个,dev,pro,test这三个文件需要自己创建,放置自己的配置文件。

 

    三、激活

在这里提供两种激活配置文件的方法

1、使用maven命令

前提是安装了maven,并且整合到了idea(或者eclipse),本人用的是idea,直接输入命令       

       mvn clean install -Pdev

       mvn clean install -Ppro

       mvn clean install -Ptest

2、使用IDEA的maven插件

查看是否有maven,点击2所指的那个向下箭头,选择Edit  Configurations,点击加号,添加一个maven,修改三个地方,箭头三所指的地方,必须要和文件的名字一样,配置好之后点击执行,三个文件都要执行一遍

三、使用

使用的话就是一般的读取配置文件,这里提供两种方式:

1、this.getClass.getClassLoader.getResourceAsStream("conf.properties")

  val properties = new Properties()
  val input = this.getClass.getClassLoader.getResourceAsStream("conf.properties")
  properties.load(input)
  def getInt(key:String):Int={
    Integer.parseInt(properties.getProperty(key))
  }
  def getString(key:String):String={
    properties.getProperty(key)
  }

       2、ConfigFactory.load("conf.properties")

 这两种方式都可以直接读取资源目录(dev,pro,test)下的资源文件

猜你喜欢

转载自blog.csdn.net/weixin_40126236/article/details/90340891