java根据不同环境使用不同的配置文件

一、maven编译打包方式 

<profiles>
    <profile>
        <id>preonline</id>
        <build>
            <resources>
                <resource>
                    <directory>src/main/resources/preonline/</directory>
                </resource>
            </resources>
        </build>
    </profile>

    <profile>
        <id>online</id>
        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>
        <build>
            <resources>
                <resource>
                    <directory>src/main/resources/online/</directory>
                </resource>
            </resources>
        </build>
    </profile>

    <profile>
        <id>test</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <build>
            <resources>
                <resource>
                    <directory>src/main/resources/test/</directory>
                </resource>
            </resources>
        </build>
    </profile>
</profiles>
    static {
        Properties properties = new Properties();
        InputStream inputStream = Object.class.getResourceAsStream("/config.properties"); //这里必须是以/开始路径
        try {
            properties.load(inputStream);
            cluster = properties.getProperty("zkClusters.address");
            timeout = Integer.valueOf(properties.getProperty("zkClusters.timeout"));
            env = properties.getProperty("zkClusters.env");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
通过以下三种mvn命令进行分别打包
mvn clean package -Ptest
mvn clean package -Ppreonline
mvn clean package -Ponline

二、指定环境变量加载不同的配置文件

首先将配置文件统一放到一个目录中,然后我们在jvm虚拟机的时候通过自定义参数-D用于区分使用的配置文件,例如:-Dprofiles=preonline。

其实springboot也是这样实现的,通过 -Dspring.profiles.active=

三、其他

<build><finalname>XXXX</finalname></build>   -->  设置最终生成文件名称

猜你喜欢

转载自blog.csdn.net/xxb249/article/details/109804352