maven 利用 profile 进行多环境配置


我们在进行项目的多环境配置时,有很多种方式供我们选择,比如 SpringBoot 自带的 application-dev.yml、maven 的 profile 等。这里介绍的就是如何利用 profile 进行多环境配置。

首先,在 pom.xml 中添加你需要的 profile 配置:

    
        
        
            dev
            
                dev
            
        
        
        
            publish
            
                publish
            
        
        
        
            local
            
                local
            
            
            
                true
            
        
    

profiles 里面配置了多个 profile 文件,即 dev、publish、local 环境, 标签是为了切换环境,激活不同的环境需要。 设置为 true 表明:该 profile 是默认激活状态。

接下来,我们要将 标签设置为 true,表示启用参数化值来替换标记,而参数化值源于 filter 标签中的 properties 文件。以下是原文解释:

 Whether resources are filtered to replace tokens with parameterised values or not.
 The values are taken from the properties element and from the properties in the files listed
 in the filters element.
 
        
        
            src/main/resources/profiles/${env}/env.properties
        
        
            
                src/main/resources
                
                    **/**
                
                
                    profiles/**
                
                true
            
         
    

中引用了 的 env 属性,表示读取哪个环境变量的值,不同的 properties 文件中配置了不同环境的值:

前面说到 true 表示启用参数化值来替换标记,这是什么意思呢?我们来看看 application.yml 中要怎么表示?

server:
  port: 8080
  tomcat:
    max-threads: 800
    uri-encoding: UTF-8

spring:
  redis:
    host: ${spring.redis.host}
    timeout: ${spring.redis.timeout}
    pool:
      max-idle: ${spring.redis.pool.max-idle}
      max-active: ${spring.redis.pool.max-active}
    password: ${spring.redis.password}
    database: ${spring.redis.database}

那么问题来了,maven 怎么认识到 ${*} 这个符号是标记呢?这个标记符号是在 中的 设置的,其中 表示不需要替换的文件扩展名。

        
            
                org.apache.maven.plugins
                maven-resources-plugin
                
                    UTF-8
                    
                        ${*}
                        @
                    
                    false
                    
                        xlsx
                        store
                    
                
            
        

因此,整个流程应该是这样进行的:执行 maven compile 命令, 读取 中 properties 的属性值,然后替换 src/main/resources 下中的标记 — 诸如 ${spring.redis.host} 这些。

最后,只剩下一个问题了,怎么切换环境呢?如果你开发的工具是 IDEA,直接在旁边窗口切换即可:

如果使用命令行编译,加上 -P 选择 profile 即可,如下:

clean -U package -P dev -DskipTests=true -f pom.xml