首页 > 解决方案 > 如何使用用scala编写的maven创建一个可以在其他项目中添加和使用的jar

问题描述

我正在尝试在 scala 中创建一个简单的计算器程序,并想从中创建一个 jar。我想在其他项目中使用的那个jar,即那个类的方法

下面是代码。

package com.umarchine.JarCheck

class CustomCalculator {

  def customAdd(a: Int, b:Int): Int ={
    a+b
  }

  def customSub(a: Int, b:Int): Int ={
    a-b
  }

  def customMul(a: Int, b:Int): Int ={
    a*b
  }

  def customDiv(a: Int, b:Int): Int ={
    a/b
  }

}

现在,我已经使用 maven clean install 创建了一个 jar。用于此代码的 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.umarchine.JarCheck</groupId>
    <artifactId>calculator</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <scala.version>2.11.5</scala.version>
        <java.version>1.8</java.version>
    </properties>

    <build>
        <sourceDirectory>src/main/scala</sourceDirectory>
        <testSourceDirectory>src/test/scala</testSourceDirectory>
    </build>


</project>

在另一个项目中,我添加了如下依赖项。

<dependency>
    <groupId>com.umarchine.JarCheck</groupId>
    <artifactId>calculator</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

通过这种依赖关系,jar 被导入到另一个项目中。但是,我无法在其他项目中导入该类或使用其方法。

有什么建议么。

标签: scalamavenjar

解决方案


我为计算器编写的代码是正确的。

我唯一缺少的是 pom.xml 中的依赖项。

我在 pom.xml 中添加了下面的 maven 插件,并发布了创建的 jar 在其他项目中运行良好。

   <plugin>
        <groupId>net.alchim31.maven</groupId>
        <artifactId>scala-maven-plugin</artifactId>
        <version>3.3.1</version>
        <executions>
            <execution>
                <id>scala-compile-first</id>
                <phase>process-resources</phase>
                <goals>
                    <goal>add-source</goal>
                    <goal>compile</goal>
                </goals>
            </execution>
            <execution>
                <id>scala-test-compile</id>
                <phase>process-test-resources</phase>
                <goals>
                    <goal>testCompile</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

推荐阅读