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

一、引入所对应的包

	<dependency>
            <groupId>org.glassfish.jersey.coregroupId>
            <artifactId>jersey-serverartifactId>
            <version>2.27version>
        dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containersgroupId>
            <artifactId>jersey-container-grizzly2-httpartifactId>
            <version>2.27version>
        dependency>
        <dependency>
            <groupId>org.glassfish.jersey.injectgroupId>
            <artifactId>jersey-hk2artifactId>
            <version>2.27version>
        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.(ApplicationHandler.java:282)
	at org.glassfish.jersey.server.ApplicationHandler.(ApplicationHandler.java:269)
	at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.(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

你可能感兴趣的:(Jersey)