【Maven jar】打包單個或多個檔案,有依賴jar包的將架包一起打包成一個jar包供別的專案引用
之前有一片文章,是打包單個java檔案的。這次想要將http://www.cnblogs.com/sxdcgaq8080/p/8398780.html 打包成jar包,發現這個java檔案中引用了多個第三方的jar,想要單獨進行編譯都無法通過,更不要說打包成jar了。
所以就營運而生了這個需求,怎麼打包單個java檔案或多個java檔案,將檔案中引用的依賴的jar包共同打包成一個jar供別的專案引用。
本次本篇使用的工具是Maven中的
maven-assembly-plugin
外掛。
======================================================================================================
1.首先,需要新建一個maven專案,將單個或多個java檔案拷貝到本專案中
例如,下面這個QR_Code.java檔案
package com.sxd.util; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.*; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; import com.google.zxing.*;View Codeimport com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.QRCodeReader; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;/** * 二維碼工具類 * @author SXD * @Date 2018.2.1 * */ public class QR_Code { private static int BLACK = 0x000000; private static int WHITE = 0xFFFFFF; /** * 內部類,設定二維碼相關引數 */ @Data(staticConstructor = "of") @NoArgsConstructor @AllArgsConstructor @Accessors(chain = true) public class CodeModel { /** * 正文 */ private String contents; /** * 二維碼寬度 */ private int width = 400; /** * 二維碼高度 */ private int height = 400; /** * 圖片格式 */ private String format = "png"; /** * 編碼方式 */ private String character_set = "utf-8"; /** * 字型大小 */ private int fontSize = 12; /** * logo */ private File logoFile; /** * logo所佔二維碼比例 */ private float logoRatio = 0.20f; /** * 二維碼下文字 */ private String desc; private int whiteWidth;//白邊的寬度 private int[] bottomStart;//二維碼最下邊的開始座標 private int[] bottomEnd;//二維碼最下邊的結束座標 } /** * 1.建立最原始的二維碼圖片 * @param info * @return */ private BufferedImage createCodeImage(CodeModel info){ String contents = info.getContents() == null || "".equals(info.getContents()) ? "暫無內容" : info.getContents();//獲取正文 int width = info.getWidth();//寬度 int height = info.getHeight();//高度 Map<EncodeHintType, Object> hint = new HashMap<EncodeHintType, Object>(); hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//設定二維碼的糾錯級別【級別分別為M L H Q ,H糾錯能力級別最高,約可糾錯30%的資料碼字】 hint.put(EncodeHintType.CHARACTER_SET, info.getCharacter_set());//設定二維碼編碼方式【UTF-8】 hint.put(EncodeHintType.MARGIN, 0); MultiFormatWriter writer = new MultiFormatWriter(); BufferedImage img = null; try { //構建二維碼圖片 //QR_CODE 一種矩陣二維碼 BitMatrix bm = writer.encode(contents, BarcodeFormat.QR_CODE, width, height, hint); int[] locationTopLeft = bm.getTopLeftOnBit(); int[] locationBottomRight = bm.getBottomRightOnBit(); info.setBottomStart(new int[]{locationTopLeft[0], locationBottomRight[1]}); info.setBottomEnd(locationBottomRight); int w = bm.getWidth(); int h = bm.getHeight(); img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); for(int x=0;x<w;x++){ for(int y=0;y<h;y++){ img.setRGB(x, y, bm.get(x, y) ? BLACK : WHITE); } } } catch (WriterException e) { e.printStackTrace(); } return img; } /** * 2.為二維碼增加logo和二維碼下文字 * logo--可以為null * 文字--可以為null或者空字串"" * @param info * @param output */ private void dealLogoAndDesc(CodeModel info, OutputStream output){ //獲取原始二維碼圖片 BufferedImage bm = createCodeImage(info); //獲取Logo圖片 File logoFile = info.getLogoFile(); int width = bm.getWidth(); int height = bm.getHeight(); Graphics g = bm.getGraphics(); //處理logo if(logoFile!=null && logoFile.exists()){ try{ BufferedImage logoImg = ImageIO.read(logoFile); int logoWidth = logoImg.getWidth(); int logoHeight = logoImg.getHeight(); float ratio = info.getLogoRatio();//獲取Logo所佔二維碼比例大小 if(ratio>0){ logoWidth = logoWidth>width*ratio ? (int)(width*ratio) : logoWidth; logoHeight = logoHeight>height*ratio ? (int)(height*ratio) : logoHeight; } int x = (width-logoWidth)/2; int y = (height-logoHeight)/2; //根據logo 起始位置 和 寬高 在二維碼圖片上畫出logo g.drawImage(logoImg, x, y, logoWidth, logoHeight, null); }catch(Exception e){ e.printStackTrace(); } } //處理二維碼下文字 String desc = info.getDesc(); if(!(desc == null || "".equals(desc))){ try{ //設定文字字型 int whiteWidth = info.getHeight()-info.getBottomEnd()[1]; Font font = new Font("黑體", Font.BOLD, info.getFontSize()); int fontHeight = g.getFontMetrics(font).getHeight(); //計算需要多少行 int lineNum = 1; int currentLineLen = 0; for(int i=0;i<desc.length();i++){ char c = desc.charAt(i); int charWidth = g.getFontMetrics(font).charWidth(c); if(currentLineLen+charWidth>width){ lineNum++; currentLineLen = 0; continue; } currentLineLen += charWidth; } int totalFontHeight = fontHeight*lineNum; int wordTopMargin = 4; BufferedImage bm1 = new BufferedImage(width, height+totalFontHeight+wordTopMargin-whiteWidth, BufferedImage.TYPE_INT_RGB); Graphics g1 = bm1.getGraphics(); if(totalFontHeight+wordTopMargin-whiteWidth>0){ g1.setColor(Color.WHITE); g1.fillRect(0, height, width, totalFontHeight+wordTopMargin-whiteWidth); } g1.setColor(new Color(BLACK)); g1.setFont(font); g1.drawImage(bm, 0, 0, null); width = info.getBottomEnd()[0]-info.getBottomStart()[0]; height = info.getBottomEnd()[1]+1; currentLineLen = 0; int currentLineIndex = 0; int baseLo = g1.getFontMetrics().getAscent(); for(int i=0;i<desc.length();i++){ String c = desc.substring(i, i+1); int charWidth = g.getFontMetrics(font).stringWidth(c); if(currentLineLen+charWidth>width){ currentLineIndex++; currentLineLen = 0; g1.drawString(c, currentLineLen + whiteWidth, height+baseLo+fontHeight*(currentLineIndex)+wordTopMargin); currentLineLen = charWidth; continue; } g1.drawString(c, currentLineLen+whiteWidth, height+baseLo+fontHeight*(currentLineIndex) + wordTopMargin); currentLineLen += charWidth; } g1.dispose(); bm = bm1; }catch(Exception e){ e.printStackTrace(); } } try{ ImageIO.write(bm, (info.getFormat() == null || "".equals(info.getFormat())) ? info.getFormat() : info.getFormat(), output); }catch(Exception e){ e.printStackTrace(); } } /** * 3.建立 帶logo和文字的二維碼 * @param info * @param file */ public void createCodeImage(CodeModel info, File file){ File parent = file.getParentFile(); if(!parent.exists())parent.mkdirs(); OutputStream output = null; try{ output = new BufferedOutputStream(new FileOutputStream(file)); dealLogoAndDesc(info, output); output.flush(); }catch(Exception e){ e.printStackTrace(); }finally{ try { output.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 3.建立 帶logo和文字的二維碼 * @param info * @param filePath */ public void createCodeImage(CodeModel info, String filePath){ createCodeImage(info, new File(filePath)); } /** * 4.建立 帶logo和文字的二維碼 * @param filePath */ public void createCodeImage(String contents,String filePath){ CodeModel codeModel = new CodeModel(); codeModel.setContents(contents); createCodeImage(codeModel, new File(filePath)); } /** * 5.讀取 二維碼 獲取二維碼中正文 * @param input * @return */ public String decode(InputStream input){ Map<DecodeHintType, Object> hint = new HashMap<DecodeHintType, Object>(); hint.put(DecodeHintType.POSSIBLE_FORMATS, BarcodeFormat.QR_CODE); String result = ""; try{ BufferedImage img = ImageIO.read(input); int[] pixels = img.getRGB(0, 0, img.getWidth(), img.getHeight(), null, 0, img.getWidth()); LuminanceSource source = new RGBLuminanceSource(img.getWidth(), img.getHeight(), pixels); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); QRCodeReader reader = new QRCodeReader(); Result r = reader.decode(bitmap, hint); result = r.getText(); }catch(Exception e){ result="讀取錯誤"; } return result; } }
2.完善pom.xml檔案,除了專案中依賴的jar的引用,還需要maven-assembly-plugin外掛
<?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.sxd.util</groupId> <artifactId>QR_Code</artifactId> <version>1.1-SNAPSHOT</version> <dependencies> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.20</version> </dependency> <!-- google提供二維碼生成和解析https://mvnrepository.com/artifact/com.google.zxing/core --> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <artifactId> maven-assembly-plugin </artifactId> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> <archive> <manifest> <mainClass>com.sxd.util.QR_Code</mainClass> </manifest> </archive> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>View Code
=============================================================================================================================================
【解釋一下,直接使用的可以跳過】:
》》(1)打包出來的jar包,是以
<groupId>com.sxd.util</groupId> <artifactId>QR_Code</artifactId> <version>1.1-SNAPSHOT</version>
{artifactId}-{version}.jar命名的
》》(2)maven-assembly-plugin外掛中
預設情況下,maven-assembly-plugin內建了幾個可以用的assembly descriptor:
- bin : 類似於預設打包,會將bin目錄下的檔案打到包中
- jar-with-dependencies : 會將所有依賴都解壓打包到生成物中【本次需求正好是將所有依賴也打包】
- src :只將原始碼目錄下的檔案打包
- project : 將整個project資源打包
》》(3)針對於maven-assembly-plugin外掛中的
===================================================================================================================================================
3.使用IDEA的同志們,雙擊外掛 即可執行打包指令
執行完整的語句如下:
"C:\Program Files\Java\jdk1.8.0_131\bin\java" -Dmaven.multiModuleProjectDirectory=G:\ideaProjects\B\sxdproject -Dmaven.home=C:\Users\SXD\AppData\Local\JetBrains\Toolbox\apps\IDEA-U\ch-0\173.3727.127\plugins\maven\lib\maven3 -Dclassworlds.conf=C:\Users\SXD\AppData\Local\JetBrains\Toolbox\apps\IDEA-U\ch-0\173.3727.127\plugins\maven\lib\maven3\bin\m2.conf -javaagent:C:\Users\SXD\AppData\Local\JetBrains\Toolbox\apps\IDEA-U\ch-0\173.3727.127\lib\idea_rt.jar=58262:C:\Users\SXD\AppData\Local\JetBrains\Toolbox\apps\IDEA-U\ch-0\173.3727.127\bin -Dfile.encoding=UTF-8 -classpath C:\Users\SXD\AppData\Local\JetBrains\Toolbox\apps\IDEA-U\ch-0\173.3727.127\plugins\maven\lib\maven3\boot\plexus-classworlds-2.5.2.jar org.codehaus.classworlds.Launcher -Didea.version=2017.3 org.apache.maven.plugins:maven-assembly-plugin:2.2-beta-5:assembly [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building QR_Code 1.1-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] >>> maven-assembly-plugin:2.2-beta-5:assembly (default-cli) > package @ QR_Code >>> [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ QR_Code --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] Copying 0 resource [INFO] [INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ QR_Code --- [INFO] Changes detected - recompiling the module! [WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent! [INFO] Compiling 1 source file to G:\ideaProjects\B\sxdproject\target\classes [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ QR_Code --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory G:\ideaProjects\B\sxdproject\src\test\resources [INFO] [INFO] --- maven-compiler-plugin:3.7.0:testCompile (default-testCompile) @ QR_Code --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ QR_Code --- [INFO] No tests to run. [INFO] [INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ QR_Code --- [INFO] Building jar: G:\ideaProjects\B\sxdproject\target\QR_Code-1.1-SNAPSHOT.jar [INFO] [INFO] --- maven-assembly-plugin:2.2-beta-5:single (make-assembly) @ QR_Code --- [INFO] META-INF/MANIFEST.MF already added, skipping [INFO] Building jar: G:\ideaProjects\B\sxdproject\target\QR_Code-1.1-SNAPSHOT-jar-with-dependencies.jar [INFO] META-INF/MANIFEST.MF already added, skipping [INFO] [INFO] <<< maven-assembly-plugin:2.2-beta-5:assembly (default-cli) < package @ QR_Code <<< [INFO] [INFO] --- maven-assembly-plugin:2.2-beta-5:assembly (default-cli) @ QR_Code --- [INFO] META-INF/MANIFEST.MF already added, skipping [INFO] Building jar: G:\ideaProjects\B\sxdproject\target\QR_Code-1.1-SNAPSHOT-jar-with-dependencies.jar [INFO] META-INF/MANIFEST.MF already added, skipping [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 3.319 s [INFO] Finished at: 2018-02-01T16:30:47+08:00 [INFO] Final Memory: 23M/258M [INFO] ------------------------------------------------------------------------ Process finished with exit code 0View Code
4.執行完成之後,專案結構會發生變化
當然,想更改jar的名字,也可以直接修改完成之後再進行如下操作
開啟DOM視窗,執行如下命令
mvn deploy:deploy-file -DgroupId=sxd.jar -DartifactId=QR_Code -Dversion=1.1 -Dpackaging=jar -Dfile=G:\test\QR_Code-1.1-SNAPSHOT.jar -Durl=http://localhost:8081/repository/myself_hosted/ -DrepositoryId=myself_hosted
在http://localhost:8081/ 訪問nexus
查詢就可檢視到
這樣在專案中引用如下:
<!--QR_Code二維碼使用工具包--> <dependency> <groupId>sxd.jar</groupId> <artifactId>QR_Code</artifactId> <version>1.1</version> </dependency>
6.最後,就可以把這個單獨建立的專案 刪除就好了
END
=========================================
參考地址:https://www.cnblogs.com/f-zhao/p/6929814.html
相關推薦
【Maven jar】打包單個或多個檔案,有依賴jar包的將架包一起打包成一個jar包供別的專案引用
之前有一片文章,是打包單個java檔案的。這次想要將http://www.cnblogs.com/sxdcgaq8080/p/8398780.html 打包成jar包,發現這個java檔案中引用了多個第三方的jar,想要單獨進行編譯都無法通過,更不要說打包成jar了。 所以就營運而生了這個需求,怎麼打包單
正則表示式匹配單個或多個單詞,不區分大小寫
比如我們在input框中要保證不能出現delete和drop,我們可以使用正則表示式。 var input = document.querySelector('input'); var btn = document.querySelector('butt
jspsmartupload元件實現單個或多個檔案上傳(下)
///實現新增多個附件 <%@ page language="java" pageEncoding="GBK"%> <html> <head> <title>struts upload by zhangc</titl
ant單個或多個渠道包打包參考文件
操作方法: 1、 單個渠道包 1、下載ant,並配置環境變數 並且配置AndroidSDKTools環境變數 2、測試ant以及android命令是否安裝成功,下圖表明已安裝成功 3、build.xml和 local.properties目錄自動生成 執行cm
Python + Appium 【已解決】driver(session)在多個class之間復用,執行完一個類的用例,再次執行下個類的用例時不需要初始化
nic bject config com appium client lee session ted py文件的名稱為:appium_config.py 中的寫法如下 # coding=UTF-8 ‘‘‘ Created on 2017.1.13 @author: Lu
java 從字串中 以單個或多個空格進行分隔 提取字串
String str = "test test1 test2 test3"; String [] arr = str.split("\\s+"); for(String ss : arr){
linux 用 grep 查找單個或多個字符串(關鍵字)
grep 關鍵字 inux rep tmp php lin log 成功 1.單個 cat /tmp/php.log | grep "成功" 所有的成功都會被查詢出來。 2.多個,並列查詢 cat /tmp/php.log | grep "推薦
【漏洞預警】CNNVD關於微軟多個安全漏洞的通報
前言 近日,微軟官方釋出了多個安全漏洞的公告,包括Microsoft Internet Explorer 安全漏洞(CNNVD-201812-458、CVE-2018-8619)、Microsoft Excel安全漏洞(CNNVD-201812-466、CVE-2018-8597)等多個漏洞。成
linux 用 grep 查詢單個或多個字串(關鍵字)
1、單個字串進行查詢:1、查詢當前目錄檔名中的字串: grep 字串 檔名2、查詢某個檔案中字串,並輸出行號:grep -n 字串 檔名3、查詢當前目錄(包含子目錄)的字串:grep -r 字串 *4、查詢當前目錄(包含子目錄)的字串,並輸出行號:grep -rn
【程式碼筆記】iOS-scrollerView裡多個tableView加搜尋框
#import "RootViewController.h" #import "customCell.h" @interface RootViewController () @end @implementation RootViewController - (id)initWithNibName:(N
【JS筆記】頁面同時載入多個函式
《Javascript高階程式設計》 1.頁面需要繫結少量函式時可以用下面方法,使用匿名函式繫結所需要執行的函式: window.onload = function(){ firstFunction(); secondFunction(); } 2.推薦方
mybatis針對Oracle資料庫進行(單個或多個條件)批量操作(新增、修改、刪除)的sql寫法--mysql
1、批量新增: <insert id="addMonthDutyIntoDB" parameterType="java.util.List"> insert into TB_D
【Android筆記】用Intent在多個Activity之間傳遞引數
一、向下一個活動傳遞資料 前面我們在介紹Intent的時候有說過,我們可以利用Intent在不同元件之間傳遞資料,接下來這篇文章就是記錄如何利用Intent在不同Activity之間傳遞簡單資料、傳遞資料包、傳遞值物件以及返回資料給上一個活動的
小程序攜帶參數(單個或多個)跳轉頁面(實例)
-i con -name func tar pre ons 是你 傳遞數據 小程序html部分 data為傳遞至js的變量 name和id為變量名 <button class="an" data-name="鈞一" data-id="888" bindtap=
項目案例【Net Core】如何註入多個服務實現類
val sage ons bre order exce let else 錯誤信息 需求 庫表保存時,需要校驗邏輯. 提交時有更深層次校驗. **狀態,還有特殊校驗 接口 寫一個通用的校驗接口,這裏定義了校驗時間.每個階段校驗可能需要考慮順序,增加一個順序字段.
章節十二、2-如何封裝一個查詢單個或多個元素的通用方法
從這一節開始,不講基本的頁面操作了,開始為搭建框架做準備,例如如何封裝查詢元素的通用方法,這個方法封裝好後其它類中都可以使用封裝好的這個方法來查詢元素,提高程式碼的複用性,方便後期維護。 一、首先我們需要封裝一個能夠定位單個或多個元素的類 1 package usefulmethod
【面試必備】用了那麼多次 ping,是時候知道 ping 是如何工作的了!
每日一句英語學習,每天進步一點點: 前言 在日常生活或工作中,我們在判斷與對方網路是否暢通,使用的最多的莫過於 ping 命令了。 “那你知道 ping 是如何工作的嗎?” —— 來自小林的靈魂拷問 可能有的小夥伴奇怪的問:“我雖然不明白它的工
C#.架構設計 資料(二)c# 專案中包含了多個模組或多個功能,如何靈活開啟/關閉、新增/刪除某個模組或功能
一、簡介 不知不覺,短短几個月的時間,我已經寫了大大小小100篇部落格。短短几個月的時間,見證了我的努力、我的收穫、我的學習效率。從一開始的零基礎,到現在我需要了解整個專案的設計架構,才能來滿足我的設計需求。
Visual Studio 找不到一個或多個元件,請重新安裝該應用程式
開啟 Visual Studio 的時候,彈出如下的對話方塊: 出現上述問題的原因是少了某些元件,原因可能是安裝目目錄下的檔案被誤刪或是被防毒軟體隔離了,如果是誤刪的話,重新找到該檔案將其恢復至原來位置即可。如果是被防毒軟體隔離了,就需要找到病毒查殺模組下的“恢復區”找到被隔離檔案並恢復即可。
【R語言】R讀取含中文excel檔案,read.xlsx亂碼問題
最近在做一個汽車銷售量的分析,在匯入xlsx檔案的時候總是出現亂碼,因為本來就在excel裡做了部分的資料清洗和整理,所以資料其實已經挺乾淨的,但就是會出現亂碼 這是原始的資料表: 匯入的時候使用xlsx.read 錯誤1:沒有插入Encoding引數