当前位置: 首页 > 工具软件 > Grizzly > 使用案例 >

Jersey——搭建Jersey + Grizzly开发环境

公孙阳羽
2023-12-01

一、引入所对应的包

	<dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.27</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-grizzly2-http</artifactId>
            <version>2.27</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.inject</groupId>
            <artifactId>jersey-hk2</artifactId>
            <version>2.27</version>
        </dependency>

注意:请务必引入最后一个依赖,否则会报如下错误:

Exception in thread "main" java.lang.IllegalStateException: InjectionManagerFactory not found.
	at org.glassfish.jersey.internal.inject.Injections.lambda$lookupInjectionManagerFactory$0(Injections.java:98)
	at java.util.Optional.orElseThrow(Optional.java:290)
	at org.glassfish.jersey.internal.inject.Injections.lookupInjectionManagerFactory(Injections.java:98)
	at org.glassfish.jersey.internal.inject.Injections.createInjectionManager(Injections.java:93)
	at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:282)
	at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:269)
	at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.<init>(GrizzlyHttpContainer.java:334)
	at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory.createHttpServer(GrizzlyHttpServerFactory.java:138)
	at com.jersey.Main.main(Main.java:15)

二、启动Grizzly代码

public class Main {
    private static final URI BASE_URI = URI.create("http://localhost:8080/base/");

    public static void main(String[] args) throws Exception {
        System.out.println("Hello world Jersey Example App!");
        final HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, createResourceConfig(), false);
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                httpServer.shutdownNow();
            }
        }));
        httpServer.start();
        System.out.println("Application started.Try out Stop the application using CTRL+C!");
        Thread.currentThread().join();
    }

    public static ResourceConfig createResourceConfig() {
        ResourceConfig config = new ResourceConfig();
        config.register(HelloResource.class);
        return config;
    }
}

三、Resource代码

@Path("hello")
public class HelloResource {

    @Path("")
    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    public String hello() {
        return "hello world!";
    }
}

码云地址

四、参考链接

  1. jersey-server-grizzly2
  2. java.lang.IllegalStateException: InjectionManagerFactory not found解决办法
  3. jersey-stopped-working-with-injectionmanagerfactory-not-found
 类似资料: