java application maven项目打自定义zip包


1.配置pom.xml文件,添加build节点


        
        p2p
        src/main/java

        
            
            
                src/main/resources
                
                    **/*.properties
                    **/*.xml
                
                
                
                    config.properties
                
            
            
           
                src/main/resources
                
                    config.properties
                
                ${project.build.directory}/config
           
       

       
           
            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.1
                
                    1.7
                    1.7
                    UTF-8
                
            

            
            
                org.apache.maven.plugins
                maven-jar-plugin
                
                    
                        
                        
                            com.hdwang.Application
                            true
                            lib/
                        
                        
                        
                            config/
                        
                    
                    
                    
                
            

org.apache.maven.plugins maven-dependency-plugin copy package copy-dependencies ${project.build.directory}/lib

org.apache.maven.plugins maven-resources-plugin 2.5 UTF-8 org.apache.maven.plugins maven-assembly-plugin 2.2.1 src/main/assembly/assembly.xml make-assembly package single

这个pom配置文件中注意红色字体部分,这是实现配置文件外置的关键配置,思路就是配置文件不打进jar包,放置到外面,且将此文件夹设置为classpath,这样子程序便可以通过根据classloader很方便地读取到配置文件了。下面给出读取配置文件的java代码,在IDE运行时和打包后,代码都不用修改,因为配置文件总能从classpath路径中找到!!!

工具包的maven信息


commons-configuration
commons-configuration
1.10

2.新建maven-assembly-plugin插件的配置文件assembly.xml,内容如下


    bin
    
        zip
    
    
    
        
            
            
            
        
    
    
        
        
            target
            
                *.jar
            
            /
        
        
            target/lib
            /lib
        
        
            target/config
            /config
        

        
        
            src/main/run
            
                *.sh
                *.cmd
            
            /
        
        
            src/main
            
                ReadMe.txt
            
            /
        
    

这个插件在package生命周期中运行,执行mvn package或者mvn install便可触发此插件的执行。这里我注释掉了拷贝依赖包的代码,是因为在pom.xml文件中已经配置了maven-dependency-plugin执行这样的操作,无须重复配置。fileSet可以配置需要拷贝压缩的文件,directory路径相对于项目根目录,outputDirectory路径相对于输出目录target,includes可以对拷贝的文件进行筛选。这里可以拷贝压缩输出目录的文件,应该就是因为此插件运行在程序编译打包之后,这样子就达到了我们自定义打包的要求:编译->拷贝资源文件->项目打包->拷贝依赖的jar包-> assembly进行拷贝压缩。然后使用打出的zip包就可以去部署发布了,解压后就能运行。

3.程序打包流程示意图