在Spring项目中添加自定义依赖项后,缺少类

时间:2020-02-05 13:27:22

标签: java spring spring-boot maven maven-jar-plugin

为了避免代码重复,我决定在基于spring的库项目中打包一些类。以下是我采取的步骤:

  1. 使用spring initialzr创建的项目。
  2. 创建所需的结构并添加类。
  3. 已删除的主要班级
  4. 已添加到pom.xml必需的依赖项中
  5. 已添加到pom.xml插件maven-jar-plugin

enter image description here

  1. 创建了简单的脚本来自动打包和安装对本地maven存储库的依赖关系:
    #!/usr/bin/env bash

    POM="pom.xml"
    ARTIFACT="springbot-messenger-client"

    MVN_VERSION=$(mvn -q -f $POM \
        -Dexec.executable=echo \
        -Dexec.args='${project.version}' \
        --non-recursive \
        exec:exec)

    mvn package -f $POM
    mvn install:install-file \
    -Dfile="target/"$ARTIFACT"-"$MVN_VERSION".jar" \
    -DgroupId=ai.optime \
    -DartifactId=$ARTIFACT \
    -Dversion=$MVN_VERSION \
    -Dpackaging=jar

    echo "Version "$MVN_VERSION" of "$ARTIFACT" installed"

  1. 脚本执行成功,并且我将新创建的依赖项添加到另一个项目中。

在应用程序启动期间,我有一个例外:

Caused by: java.lang.ClassNotFoundException: com.fasterxml.jackson.dataformat.yaml.YAMLFactory

YAMLFactory属于依赖项jackson-dataformat-yaml,它已添加到库项目的pom.xml中:

enter image description here

据我了解,mvn package不包含依赖项,那么如何正确地包含它们呢?我知道 fat jar 的概念,但这可能不是正确的解决方案。

1 个答案:

答案 0 :(得分:0)

我用来编译spring应用程序的是:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${maven-compiler.version}</version>
            <configuration>
                <source>11</source>
                <target>11</target>
                <release>11</release>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <fork>true</fork>
                <mainClass>path.to.main.class</mainClass>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

还有

mvn全新安装

,它将生成具有所有依赖项的jar。

希望对您有帮助。