IDEA中配置properties文件

自从生产环境权限回收后,各种问题同时出现:测试数据库和生产数据库不一致,测试集群配置和生产集群配置文件不一致等等问题,十分难受,,,
我承认是之前开发不规范,呃呃呃。。。
于是决定采用scala读取jar包内配置文件的方式:
在这里插入图片描述
(1)在resources目录下新建 pro和test子目录
新建config.properties文件

hive.database = test

(2)修改pom.xml打包方式
新增profiles

<profiles>
        <profile>
            <!-- 测试环境 -->
            <id>test</id>
            <properties>
                <profiles.active>test</profiles.active>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <profile>
            <!-- 生产环境 -->
            <id>pro</id>
            <properties>
                <profiles.active>pro</profiles.active>
            </properties>
        </profile>
    </profiles>

修改build下resources

 <resources>
            <resource>
                <directory>src/main/resources</directory>
                <excludes>
                    <exclude>test/*</exclude>
                    <exclude>pro/*</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources/${profiles.active}</directory>
            </resource>
        </resources>

(3)封装ConfigManager类

import java.util.Properties
object ConfigManager {

    def main(args: Array[String]): Unit = {
        println(getConfigValue("hive.database","pro/config.properties"))
    }
    /**
      * 获取配置名称
      */
    def getConfigValue(key : String,path:String="config.properties"): String = {
    val stream =Thread.currentThread.getContextClassLoader.getResourceAsStream(path)
    val prop : Properties= new Properties()
    prop.load(stream)
    prop.getProperty(key)
    }
}

其中通过修改pom.xml来切换test和pro配置文件,
本地测试&打集群测试均OK,完美解决多环境问题~

发布了118 篇原创文章 · 获赞 25 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/lhxsir/article/details/90903903