Idea Java Maven建立專案,新增依賴,引用本地jar,打包jar

紅色與青色發表於2021-01-05

idea版本:2020.2

首先建立專案,選Maven,勾上Create from archetype,選maven-archetype-quickstart

填好專案名和包名 ,然後Next

我這裡使用預設的,直接Finish

等待建立完成

右上角同樣無法run

在APP.java類內右鍵->Run 'App.main()'

看到輸出Hello World!

試著在pom.xml新增okhttp

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.squareup.okhttp3</groupId>
      <artifactId>okhttp</artifactId>
      <version>4.9.0</version>
    </dependency>
  </dependencies>

按ctrl+shift+o重新整理一下或者按下下圖按鈕

在App.main()函式內寫上okhttp程式碼測試一下

package com.hyq.hm.test.maven;

import okhttp3.*;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.Objects;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
        String url = "https://www.baidu.com";
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                System.out.println("onFailure");//測試
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                System.out.println("onResponse: " + Objects.requireNonNull(response.body()).string());
            }
        });
    }
}

run一下

成功

接下來新增本地jar包了,同樣拿opencv 4.4.0來舉例
首先在專案目錄內建立一個lib資料夾

將opencv的jar包複製到lib資料夾內

點選idea的右上角的Edit Configurations...

在VM options:內填上opencv_java440.dll的資料夾路徑-Djava.library.path=X:/opencv/build/java/x64

在pom.xml的dependencies新增程式碼

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.opencv</groupId>
            <artifactId>opencv</artifactId>
            <version>4.4.0</version>
        </dependency>
    </dependencies>

再在build內的maven-install-plugin內填上程式碼,最後我會貼上完整pom.xml

<plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
          <executions>
            <execution>
              <id>install-opencv</id>
              <phase>clean</phase>
              <configuration>
                <file>${basedir}/lib/opencv-440.jar</file>
                <repositoryLayout>default</repositoryLayout>
                <groupId>com.opencv</groupId>
                <artifactId>opencv</artifactId>
                <version>4.4.0</version>
                <packaging>jar</packaging>
                <generatePom>true</generatePom>
              </configuration>
              <goals>
                <goal>install-file</goal>
              </goals>
            </execution>
          </executions>
        </plugin>

ctrl+shift+o重新整理一下

建立ImageGUI.java來顯示,也可以跳過這個,我只是顯示看看更直觀

package com.hyq.hm.test.maven;
import org.opencv.core.Mat;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;

public class ImageGUI extends JComponent{
    private BufferedImage image;
    @Override
    protected void paintComponent(Graphics g) {
        int width = g.getClipBounds().width;
        int height = g.getClipBounds().height;
        Graphics2D g2d = (Graphics2D)g;
        g2d.setPaint(Color.WHITE);
        g2d.fillRect(0, 0, width, height);
        if(image != null)  {
            int[] rect = viewportSize(width, height,image.getWidth(),image.getHeight());
            g2d.drawImage(image, rect[0], rect[1], rect[2], rect[3], null);
        }
    }
    private JFrame ui;
    public void createWin(String title) {
        ui = new JFrame();
        ui.setLayout(null);
        ui.setTitle(title);
        ui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        int viewWidth = 800;
        int viewHeight = (int) (9.0f/16.0f*viewWidth);
        setBounds(0,0,viewWidth,viewHeight);
        ui.add(this);
        ui.setSize(viewWidth,viewHeight);
        ui.setVisible(true);
        ui.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                int width = ui.getSize().width;
                int height = ui.getSize().height;
                setSize(width, height);
            }
        });
    }
    private int[] viewportSize(int screenWidth, int screenHeight, int width, int height) {
        int left, top, viewWidth, viewHeight;
        float sh = screenWidth * 1.0f / screenHeight;
        float vh = width * 1.0f / height;
        if (sh < vh) {
            left = 0;
            viewWidth = screenWidth;
            viewHeight = (int) (height * 1.0f / width * viewWidth);
            top = (screenHeight - viewHeight) / 2;
        } else {
            top = 0;
            viewHeight = screenHeight;
            viewWidth = (int) (width * 1.0f / height * viewHeight);
            left = (screenWidth - viewWidth) / 2;
        }
        return new int[]{left, top, viewWidth, viewHeight};
    }
    public void imageShow(BufferedImage image) {
        this.image = image;
        this.repaint();
    }
    public void matShow(Mat mat){
        this.image = toImage(mat);
        this.repaint();
    }
    public static BufferedImage toImage(Mat matrix) {
        int type = BufferedImage.TYPE_BYTE_GRAY;
        if (matrix.channels() == 3) {
            type = BufferedImage.TYPE_3BYTE_BGR;
        }else if(matrix.channels() == 4){
            type = BufferedImage.TYPE_4BYTE_ABGR;
        }
        int bufferSize = matrix.channels() * matrix.cols() * matrix.rows();
        byte[] buffer = new byte[bufferSize];
        matrix.get(0, 0, buffer);
        BufferedImage image = new BufferedImage(matrix.cols(), matrix.rows(), type);
        final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
        System.arraycopy(buffer, 0, targetPixels, 0, buffer.length);
        return image;
    }
}

在App.java內新增上程式碼

package com.hyq.hm.test.maven;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
/**
 * Hello world!
 *
 */
public class App 
{
    static {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }
    public static void main( String[] args )
    {
        Mat mat = new Mat(100,100, CvType.CV_8UC3,new Scalar(255,0,0));
        ImageGUI gui = new ImageGUI();
        gui.createWin("test");
        gui.matShow(mat);
        System.out.println( "Hello World!" );
    }
}

run一下

好了,最後打成jar包了

首先將pom.xml內的<pluginManagement></pluginManagement>刪除,再把除maven-install-plugin以外的全部刪除

<build>
      <plugins>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
          <executions>
            <execution>
              <id>install-opencv</id>
              <phase>clean</phase>
              <configuration>
                <file>${basedir}/lib/opencv-440.jar</file>
                <repositoryLayout>default</repositoryLayout>
                <groupId>com.opencv</groupId>
                <artifactId>opencv</artifactId>
                <version>4.4.0</version>
                <packaging>jar</packaging>
                <generatePom>true</generatePom>
              </configuration>
              <goals>
                <goal>install-file</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
      </plugins>
  </build>

<version>2.5.2</version>部分會變成紅色,但是不影響打包

再新增上maven-assembly-plugin

<plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <configuration>
            <archive>
              <manifest>
                <mainClass>com.hyq.hm.test.maven.App</mainClass>
              </manifest>
            </archive>
            <descriptorRefs>
              <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
          </configuration>
          <executions>
            <execution>
              <id>make-assemble</id>
              <phase>package</phase>
              <goals>
                <goal>single</goal>
              </goals>
            </execution>
          </executions>
        </plugin>

點開右邊的Maven,雙擊Lifecycle內的package開始打包

完成後在target可以看到打好的jar包

TestMavenDemo-1.0-SNAPSHOT-jar-with-dependencies.jar是我打好的包,把其他的都刪掉,將opencv_java440.dll複製過來

使用控制檯執行一下

這只是打包的一種還有很多打包方式,慢慢研究

pom.xml

<?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.hyq.hm.test.maven</groupId>
  <artifactId>TestMavenDemo</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>TestMavenDemo</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.squareup.okhttp3</groupId>
      <artifactId>okhttp</artifactId>
      <version>4.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.opencv</groupId>
      <artifactId>opencv</artifactId>
      <version>4.4.0</version>
    </dependency>
  </dependencies>

  <build>
      <plugins>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
          <executions>
            <execution>
              <id>install-opencv</id>
              <phase>clean</phase>
              <configuration>
                <file>${basedir}/lib/opencv-440.jar</file>
                <repositoryLayout>default</repositoryLayout>
                <groupId>com.opencv</groupId>
                <artifactId>opencv</artifactId>
                <version>4.4.0</version>
                <packaging>jar</packaging>
                <generatePom>true</generatePom>
              </configuration>
              <goals>
                <goal>install-file</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
        <plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <configuration>
            <archive>
              <manifest>
                <mainClass>com.hyq.hm.test.maven.App</mainClass>
              </manifest>
            </archive>
            <descriptorRefs>
              <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
          </configuration>
          <executions>
            <execution>
              <id>make-assemble</id>
              <phase>package</phase>
              <goals>
                <goal>single</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
      </plugins>
  </build>
</project>

 

相關文章