欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Maven配置本地环境和线上环境

程序员文章站 2024-03-21 09:33:28
...

一、问题背景

有时候,我们在开发和部署的时候,有很多配置文件的数据是不一样的,比如数据库的properties文件等等每次部署或者开发都要改配置文件太麻烦了,这个时候,就需要用到maven的profile配置了

Github源码:https://github.com/jxq0816/mvn-profile-demo

Maven配置本地环境和线上环境

二、代码

1、pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.week7i.share</groupId>
  <artifactId>mvn-profile</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>mvn-profile Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
    <commons-lang3.version>3.3.2</commons-lang3.version>
    <commons-io.version>2.4</commons-io.version>
    <guava.version>17.0</guava.version>
    <junit.version>4.11</junit.version>
    <spring.version>4.3.6.RELEASE</spring.version>
  </properties>
  <dependencies>
    <!-- GENERAL UTILS begin -->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>${commons-lang3.version}</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>${commons-io.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- google java lib -->
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>${guava.version}</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>

  </dependencies>

  <build>
    <finalName>mvn-profile</finalName>
    <resources>
      <!--加载环境变量的目录-->
      <resource>
        <directory>src/main/resources/${env}</directory>
      </resource>
      <!--加载其他配置文件-->
      <resource>
        <directory>src/main/resources</directory>
        <excludes>
          <exclude>local/*</exclude>
          <exclude>online/*</exclude>
        </excludes>
      </resource>

    </resources>
  </build>

  <profiles>
    <!--开发环境-->
    <profile>
      <id>local</id>
      <properties>
        <env>local</env>
      </properties>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
    </profile>
    <!--生产环境-->
    <profile>
      <id>online</id>
      <properties>
        <env>online</env>
      </properties>
    </profile>
  </profiles>
</project>

2. 配置 local install

Maven配置本地环境和线上环境

运行local install,会在target看到本地的数据库配置文件加载成功

Maven配置本地环境和线上环境

3. 配置 maven online install

Maven配置本地环境和线上环境

运行online install,会在target看到线上的数据库配置文件加载成功

Maven配置本地环境和线上环境

三、附加功能(读取配置文件)

1、Global.java (全局配置类)

package com.weeking.share.config;

import com.google.common.collect.Maps;
import com.weeking.share.util.PropertiesLoader;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * 全局配置类
 * Created by jiangxingqi on 2017/7/27.
 */
public class Global {

    /**
     * 保存全局属性值
     */
    private static Map<String, String> map = Maps.newHashMap();

    /**
     * 属性文件加载对象
     */
    private static PropertiesLoader loader = new PropertiesLoader("jdbc.properties");

    /**
     * 获取配置
     */
    public static String getConfig(String key) {
        String value = map.get(key);
        if (value == null){
            value = loader.getProperty(key);
            map.put(key, value != null ? value : StringUtils.EMPTY);
        }
        return value;
    }
}

2. PropertiesLoader.java (配置文件读取类)

package com.weeking.share.util;

import org.apache.commons.io.IOUtils;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.util.Properties;


/**
 * Created by jiangxingqi on 2017/7/27.
 */
public class PropertiesLoader {

    private static ResourceLoader resourceLoader = new DefaultResourceLoader();

    private final Properties properties;

    public PropertiesLoader(String... resourcesPaths) {
        properties = loadProperties(resourcesPaths);
    }

    public Properties getProperties() {
        return properties;
    }

    /**
     * 取出Property,但以System的Property优先,取不到返回空字符串.
     */
    private String getValue(String key) {
        String systemProperty = System.getProperty(key);
        if (systemProperty != null) {
            return systemProperty;
        }
        if (properties.containsKey(key)) {
            return properties.getProperty(key);
        }
        return "";
    }

    /**
     * 取出String类型的Property,但以System的Property优先,如果都为Null则抛出异常.
     */
    public String getProperty(String key) {
        String value = getValue(key);
        if (value == null) {
            throw new NoSuchElementException();
        }
        return value;
    }

    /**
     * 取出String类型的Property,但以System的Property优先.如果都为Null则返回Default值.
     */
    public String getProperty(String key, String defaultValue) {
        String value = getValue(key);
        return value != null ? value : defaultValue;
    }

    /**
     * 取出Integer类型的Property,但以System的Property优先.如果都为Null或内容错误则抛出异常.
     */
    public Integer getInteger(String key) {
        String value = getValue(key);
        if (value == null) {
            throw new NoSuchElementException();
        }
        return Integer.valueOf(value);
    }

    /**
     * 取出Integer类型的Property,但以System的Property优先.如果都为Null则返回Default值,如果内容错误则抛出异常
     */
    public Integer getInteger(String key, Integer defaultValue) {
        String value = getValue(key);
        return value != null ? Integer.valueOf(value) : defaultValue;
    }

    /**
     * 取出Double类型的Property,但以System的Property优先.如果都为Null或内容错误则抛出异常.
     */
    public Double getDouble(String key) {
        String value = getValue(key);
        if (value == null) {
            throw new NoSuchElementException();
        }
        return Double.valueOf(value);
    }

    /**
     * 取出Double类型的Property,但以System的Property优先.如果都为Null则返回Default值,如果内容错误则抛出异常
     */
    public Double getDouble(String key, Integer defaultValue) {
        String value = getValue(key);
        return value != null ? Double.valueOf(value) : defaultValue;
    }

    /**
     * 取出Boolean类型的Property,但以System的Property优先.如果都为Null抛出异常,如果内容不是true/false则返回false.
     */
    public Boolean getBoolean(String key) {
        String value = getValue(key);
        if (value == null) {
            throw new NoSuchElementException();
        }
        return Boolean.valueOf(value);
    }

    /**
     * 取出Boolean类型的Property,但以System的Property优先.如果都为Null则返回Default值,如果内容不为true/false则返回false.
     */
    public Boolean getBoolean(String key, boolean defaultValue) {
        String value = getValue(key);
        return value != null ? Boolean.valueOf(value) : defaultValue;
    }

    /**
     * 载入多个文件, 文件路径使用Spring Resource格式.
     */
    private Properties loadProperties(String... resourcesPaths) {
        Properties props = new Properties();

        for (String location : resourcesPaths) {

            InputStream is = null;
            try {
                Resource resource = resourceLoader.getResource(location);
                is = resource.getInputStream();
                props.load(is);
            } catch (IOException ex) {
                System.out.println("Could not load properties from path:" + location + ", " + ex.getMessage());
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
        return props;
    }
}

3. TestProfile.java

import com.weeking.share.config.Global;
import org.junit.Test;

public class TestProfile {
    @Test
    public void profile(){
        String username= Global.getConfig("jdbc.username");
        System.out.println(username);
    }
}

4.测试类运行结果

Maven配置本地环境和线上环境