Как убедиться, что "Java" находит все необходимые классы, когда может IDE? - PullRequest
0 голосов
/ 24 апреля 2019

Я застрял здесь слишком долго. У меня есть проект Maven только с одной зависимостью:

<dependency>
        <groupId>net.sf.jasperreports</groupId>
        <artifactId>jasperreports</artifactId>
        <version>6.8.0</version>
</dependency>

Я использую IDE, и она сама установила все необходимые зависимости. Я написал простой код, который использует классы из net.sf.jasperreports. Для создания пакета я сделал mvn package, и он создал jar. Когда я пытаюсь запустить jar как java -jar myjar.jar, я получаю сообщение об ошибке Caused by: java.lang.ClassNotFoundException: net.sf.jasperreports.engine.JRDataSource

Я просто не могу понять, как я мог решить это. Среда IDE может найти классы, но при вызове из командной строки она не может найти классы. Почему это так? Что мне делать?

Я даже пытался удержать jasperreports-6.8.0.jar на /Library/Java/Extensions/, но это тоже не сработало.

Вот как выглядит 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.suhail</groupId>
    <artifactId>JasperCSVDataSource</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.suhail.main.CommandLineRunner</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <packaging>jar</packaging>

    <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>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>6.8.0</version>
        </dependency>

    </dependencies>    

</project>

Ответы [ 2 ]

0 голосов
/ 24 апреля 2019

Используйте плагин сборки Maven вместо плагина Maven jar.

см. что такое различия между maven-jar-plugin-and-maven-assembly-plugin !

Плагин сборки Maven создает полностью развертываемый пакет со всеми зависимостями, упакованными в него.

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4.1</version>
                <configuration>
                    <!-- get all project dependencies -->
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <!-- MainClass in mainfest make a executable jar -->
                    <archive>
                      <manifest>
                        <mainClass>com.suhail.main.CommandLineRunner</mainClass>
                      </manifest>
                    </archive>

                </configuration>
                <executions>
                  <execution>
                    <id>make-assembly</id>
                    <!-- bind to the packaging phase -->
                    <phase>package</phase> 
                    <goals>
                        <goal>single</goal>
                    </goals>
                  </execution>
                </executions>
            </plugin>
0 голосов
/ 24 апреля 2019

Это часть, которая использует плагин Maven Shade в моем проекте, который, конечно, полностью отличается от вашего:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>3.2.1</version>
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
    </configuration>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <shadedArtifactAttached>true</shadedArtifactAttached>
                <artifactSet>
                    <includes>
                        <include>org.apache.poi:poi</include>
                        <include>org.apache.poi:poi-ooxml</include>
                        <include>org.apache.poi:poi-ooxml-schemas</include>
                        <include>org.apache.commons:commons-collections4</include>
                        <include>org.apache.xmlbeans:xmlbeans</include>
                        <include>org.apache.commons:commons-compress</include>
                    </includes>
                    <excludes>
                        <!-- Exclude main jar to avoid error 'Failed to create shaded artifact, 
                            project main artifact does not exist' -->
                        <exclude>${project.groupId}:${project.artifactId}</exclude>
                    </excludes>
                </artifactSet>
            </configuration>
        </execution>
    </executions>
</plugin>
<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>3.1.1</version>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <appendAssemblyId>false</appendAssemblyId>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
    </configuration>
</plugin>

Обратите внимание, что эта часть pom.xml входит в раздел <plugins> ... </plugins>, в моем случае она ниже плагина компилятора maven и ниже плагина maven jar. Вы можете явно включить определенные зависимости или явно исключить определенные.

Результатом будет 2 файла в вашей целевой папке, я лично использую тот, который имеет оригинальное имя, другой будет иметь оригинальное имя, расширенное на затенено или подобное.

Если вы получаете сообщение об ошибке Нет атрибута основного манифеста в ... , измените конфигурацию подключаемого модуля maven jar следующим образом:

<configuration>
    <archive>
        <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
    </archive>
    <mainClass>com.suhail.main.CommandLineRunner</mainClass>
</configuration>
...