Maven Profile 的应用

maven 的 profile 应用 或多或少都会出现在中大型的公司中。

如果你是第一次接触maven 这个profile, 可能你并不会关心它究竟是做什么用的,就像我一样。

即使见过很多次,但是不需要自己配置,能动就好。

但是问题出现之后,你就可能发现不了什么问题了。

基本概念

Profile ,跟基本翻译出来的意思差不多,在技术翻译中就是配置的意思。根据不同的profile,运行时替换掉定义好的变量值。

如果你用过spring的profile,大概就知道怎么样了。

不同类型的profile

  • 项目级别的profile

定义POM文件中

  • 用户级别

定义在 (%USER_HOME%/.m2/settings.xml)

  • 全局 定义在 (${maven.home}/conf/settings.xml).

如何激活profile?

  • Explicitly
  • Through Maven settings
  • Based on environment variables
  • OS settings
  • Present or missing files
在 setting 配置文件中,显式启动

在配置文件中,可以在 标签内,显式指定要启动的profile

如下:


  ...
  
    profile-1
  
  ...

基于build的环境变量来启动

下面的配置代表,当jdk 版本号在 1.3 到 1.5之间的情况下,profile就会被激活


  
    
      [1.3,1.6)
    
    ...
  


下面这个则是,基于运行时的变量来指定,如果 系统变量中有“environment” 且 值为 "test"的时候,下面的profile就或被激活。

mvn groupId:artifactId:goal -Denvironment=test


    
  
    
      
        environment
        test
      
    
    ...
  


具体应用

那么实际中,可以利用profile来做什么东西?

通常在pom层面的profile的灵活性会高很多,因为这只是针对项目级别,修改profile的配置不会影响到其他的项目。

具体可以在pom中修改的内容项有如下:





 (not actually available in the main POM, but used behind the scenes)




a subset of the  element, which consists of:




这些都是可以被profile中定义的属性替换掉pom中的值。

具体例子

下面这个配置指定了一个appserver.home


  ...
  
    
      
        org.myco.plugins
        spiffy-integrationTest-plugin
        1.0
        
          ${appserver.home}
        
      
      ...
    
  
  ...


我们在POM中再加上如下的profile配置


  ...
  
    
      appserverConfig-dev
      
        
          env
          dev
        
      
      
        /path/to/dev/appserver
      
    
 
    
      appserverConfig-dev-2
      
        
          env
          dev-2
        
      
      
        /path/to/another/dev/appserver2
      
    
  
  ..

这个profile的配置被激活时,可以替换掉定义的变量值。

按照这个方法,其他的配置也可以相应的进行配置改变。

扫描二维码,进技术群一起学习成长:

你可能感兴趣的:(maven,java)