簡體   English   中英

使用 maven-assembly-plugin 創建 uber jar 時 Jersey 失敗

[英]Jersey fails when creating uber jar with maven-assembly-plugin

我創建了一個 maven jersey starter webapp。 此外,我使用 jetty 插件在我的應用程序中嵌入了碼頭服務器。

當我使用 mvn jetty:run 命令運行我的項目時,我的項目工作正常。

但是,當我使用 mvn clean package 命令打包我的項目並運行名為 jar-with-dependencies 的 jar 文件時,該項目在從球衣資源返回 json 響應時拋出此異常。

嚴重:找不到 Media type=application/json、type=class com.nitish.freecharge.model.Count、genericType=class com.nitish.freecharge.model.Count 的 MessageBodyWriter。

這是我的 pom.xml 文件

http://maven.apache.org/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.nitish.freecharge</groupId>
<artifactId>wordcount</artifactId>
<packaging>war</packaging>
<version>2.0</version>
<name>wordcount</name>

<build>
    <finalName>wordcount</finalName>
    <resources>
        <resource>
            <directory>src/main/java</directory>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
        <resource>
            <directory>src/main/webapp</directory>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.5.1</version>
            <inherited>true</inherited>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>9.3.0.v20150612</version>
            <configuration>
                <scanIntervalSeconds>5</scanIntervalSeconds>
                <webApp>
                    <contextPath>/wordcount</contextPath>
                </webApp>
                <httpConnector>
                    <!--host>localhost</host -->
                    <port>9999</port>
                </httpConnector>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <executions>
                <execution>
                    <id>package-jar</id>
                    <phase>package</phase>
                    <goals>
                        <goal>jar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <finalName>awesomeProject</finalName>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
                <appendAssemblyId>false</appendAssemblyId>
                <archive>
                    <manifest>
                        <mainClass>App</mainClass>
                    </manifest>
                </archive>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey</groupId>
            <artifactId>jersey-bom</artifactId>
            <version>${jersey.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet-core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-moxy</artifactId>
    </dependency>
    <dependency>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-server</artifactId>
        <version>9.3.8.v20160314</version>
    </dependency>
    <dependency>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-servlet</artifactId>
        <version>9.3.8.v20160314</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.4</version>
    </dependency>
</dependencies>
<properties>
    <jersey.version>2.22.2</jersey.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

我在默認包中創建了我的 Main Driver 類作為 App.java。 這是我的 App.java 內容

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

public class App {
    public static void main(String []gg){

        Server server = new Server(9999);

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);

        ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/wordcount/*");
        jerseyServlet.setInitOrder(1);
        jerseyServlet.setInitParameter("jersey.config.server.provider.packages","com.nitish.freecharge.resources");
        try {
            System.out.println("Starting the server..");
            server.start();
            System.out.println("Server started");
            server.join();
        } catch(Exception e) {
            System.out.println("Exception in starting the server ");
            e.printStackTrace();
        }
    }
}

這是我在啟動服務器后訪問我的項目 url 時執行的唯一球衣資源類:

package com.nitish.freecharge.resources;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import com.nitish.freecharge.dao.FileDAO;
import com.nitish.freecharge.model.Count;

/**
 * Root resource (exposed at "count" path) which handles HTTP GET method and returns the count value;
 */
@Path("/count")
public class CountResource {

    private FileDAO fileDAO=new FileDAO();

    /**
     * Method handling HTTP GET requests. The returned object will be sent
     * to the client as "application/json" media type.
     *
     * @return String that will be returned as a application/json response.
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @QueryParam("query")
    public Response getWordCount(@QueryParam("query")String query) {
        Error error=null;
        Count count=null;
        try{   
            if(query!=null){
                query=query.trim();
                if(query.length()>0 && query.matches("^[A-Za-z]+$")){
                    long c=fileDAO.getCount(query.toLowerCase());
                    count=new Count(c);
                }else{
                    error=new Error("Some Error Occured.Please Try Again With a new word!");
                }
            }else{
                error=new Error("Some Error Occured.Please Try Again!");
            }
        }catch(Exception e){
            error=new Error(e.getMessage());
            return Response.status(Status.INTERNAL_SERVER_ERROR).entity(error).build();
        }
        if(count!=null){
            return Response.status(Status.OK).entity(count).build();
        }else{
            return Response.status(Status.BAD_REQUEST).entity(error).build();
        }
    }
}

使用命令 java -jar awesomeProject.jar 打包並運行完整的嵌入式項目后

我在服務器提示上得到這個輸出

在此處輸入圖片說明

我已經嘗試了很多,但無法以解決此問題的方式打包我的嵌入式 web 應用程序。 我是 maven 和包裝的新手。 請幫助我犯錯誤的地方。

如果您查看 MOXy jar 的內部,您將看到一個文件夾META-INF/services 在該文件夾中,您將看到一個名為org.glassfish.jersey.internal.spi.AutoDiscoverable的文件。 該文件的內容應該是一行

org.glassfish.jersey.moxy.json.internal.MoxyJsonAutoDiscoverable

這個文件是為了讓 Jersey 發現MoxyJsonAutoDiscoverable ,它為 Jersey 注冊 MOXy。 這種服務加載器模式允許 Jersey 發現功能並注冊它們,而無需我們自己注冊它們。

這在創建 uber jar 時帶來的問題是,可能有多個 jars 具有相同的文件,因為不同的 jars 有不同的特性需要發現,但文件需要是那個確切的名稱,因為這就是服務加載器模式的工作方式。

因此,您有一堆具有相同文件的 jar,但是當您創建 uber jar 時,您不能有多個具有相同名稱的文件。 這是不可能的。 所以只有一個文件被放入最終的 jar 中。 哪一個……誰知道呢。 但這意味着如果 MOXy 的文件不是那個文件,那么它的功能將不會被自動發現,我們需要自己注冊它。 所以這些類被打包在 uber jar 中,但主要功能組件只是沒有注冊。 你可以自己注冊

jerseyServlet.setInitParameter("jersey.config.server.provider.classnames",
                               "org.glassfish.jersey.moxy.json.MoxyJsonFeature");

但是,由於未包含可自動發現的文件而可能遺漏的所有其他可能功能呢?

出於這個原因,您應該使用maven-shade-plugin而不是程序集插件,它具有轉換器,允許我們將服務文件的內容連接到一個文件中。

配置看起來像

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>2.3</version>
    <configuration>
        <createDependencyReducedPom>true</createDependencyReducedPom>
        <filters>
            <filter>
                <artifact>*:*</artifact>
                <excludes>
                    <exclude>META-INF/*.SF</exclude>
                    <exclude>META-INF/*.DSA</exclude>
                    <exclude>META-INF/*.RSA</exclude>
                </excludes>
            </filter>
        </filters>
    </configuration>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <transformers>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <mainClass>com.example.YourApp</mainClass>
                    </transformer>
                </transformers>
            </configuration>
        </execution>
    </executions>
</plugin>

ServicesResorceTransformaer連接文件。 插件的這個特殊配置來自Dropwizard 入門 您可能需要檢查一下以獲得進一步的解釋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM