maven resources导致打包失败分析与解决

今天在工作时遇到一个测试环境maven打包失败的问题。一开始的时候jenkins只显示了打包失败,没有其他的信息展示出来,在将项目拉取到本地之后,项目又可以完好地启动,于是判断可能是maven打包时出错,于是终端进入对应目录之后,输入以下命令:

mvn package -U -Denv=pre -DskipTests

果然,build failed。

现场失败信息如下:

于是Google了一下这个
maven-resource-plugin

官网对它的介绍是:

The Resources Plugin handles the copying of project resources to the output directory. There are two different kinds of resources: main resources and test resources. The difference is that the main resources are the resources associated to the main source code while the test resources are associated to the test source code.

查看了官方的介绍之后,我对它的总结如下:

我们可以使用maven-resource-plugin在构建项目时对pom文件进行动态的变量替换,比如:


    ...
    
        world
    
    ...

可以结合filter来读取资源文件中的变量设置,以此来进行变量的动态替换。

...

  my-filter-values.properties

...

properties文件中可以这么存:

your.name=hello

然后maven在进行打包的过程中会将filter中的文件内容和所有resource中的内容进行全部替换。这样的话我们可以在项目中定义一些特定的值,并且在打包过程中进行动态替换。需要替换的资源是这么指定的:

...

   
      src/main/resources
      true
   

...

官方在这里对其进行了说明:

Warning: Do not filter files with binary content like images! This will most likely result in corrupt output.

If you have both text files and binary files as resources it is recommended to have two separated folders. One folder src/main/resources (default) for the resources which are not filtered and another folder src/main/resources-filtered for the resources which are filtered.

也就是说指定资源范围内如果存在二进制文件和图片的话可能会有文件在进行过滤替换的过程中被损坏。

看到这里,我翻看了一下项目提交日志,发现有同事在最近的提交中新增了ttf文件,并且正好在我们的项目过滤替换范围之内。

看来问题可能出现在这了。按照官方文档的指示,继续查看相关说明。
官方给的方案如下:


  ...
  
    
      
        org.apache.maven.plugins
        maven-resources-plugin
        3.0.2
        
          ...
          
            pdf
            swf
          
          ...
        
      
    
    ...
  
  ...

还有一个自定义过滤器机制,可以自己查看>>自定义Custom resources filters

看完语法之后发现,其实设置过滤和上面的include域exclude用法类似。官方说明如下:

When specifying a resource directory, every file within that directory may not be used. Thus, we may have to specify only the files that we want to include or specify the files that we want to exclude.

To include a resource, we only need to add an element.

And to exclude a resource, we only need to add an element.

For example, we can have both and elements. For example, if we want to include all text files that does not contain the word “test” in their filename.


  ...
  My Resources Plugin Practice Project
  ...
  
    ...
    
      
        src/my-resources
        
          **/*.txt
        
        
          **/*test*.*
        
      
      ...
    
    ...
  
  ...

看来解决办法就在这儿了。

原有的资源文件设置如上所示,经过修改之后,变更如下:

再次打包试一下:

完美。分享一下,挖坑填坑是个技术活。

你可能感兴趣的:(java)