如何使用Guice + Jersey + Servlet将Swagger集成到Java项目中并自动生成REST API文档

时间:2018-07-24 04:12:14

标签: java rest jersey swagger guice

我有一个使用Guice和Jersey提供REST服务的应用程序。如何在Guice中配置Swagger?我已经有以下依赖项:

compile group: 'io.swagger', name: 'swagger-jersey2-jaxrs', version: '1.5.0'

如何自动生成API文档?遇到过类似问题的人,请对这种集成方法有所了解。非常感谢!

类似的向导

public class ServletContextListener extends GuiceServletContextListener {
 @Override
 protected Injector getInjector() {
    if(lifecycleInjector != null) return lifecycleInjector;
    this.lifecycleInjector = InjectorBuilder
            .fromModules(defineModules())
            .createInjector(Stage.DEVELOPMENT);
    return this.lifecycleInjector;
 }

 private List<Module> defineModules() {
    ArrayList<Module> modules = new ArrayList<>();
    modules.add(new ServletModule());
    return modules;
 }
}

JerseyServletModule类似于:

public class ServletModule extends JerseyServletModule {
@Override
protected void configureServlets() {
    bind(GuiceContainer.class).to(GovernatorServletContainer.class).asEagerSingleton();
    serve("/api/*").with(GuiceContainer.class);
}
@Provides
ResourceConfig getResourceConfig() {
    final List<String> resources = new ArrayList<>();
    resources.add("com.fasterxml.jackson.jaxrs.json");
    final String[] arrayPackages = new String[resources.size()];
    resources.toArray(arrayPackages);
    return new RestApp(ImmutableMap.<String, Object>builder()
            .put(PROPERTY_PACKAGES, arrayPackages)
            .put(FEATURE_DISABLE_WADL, "true")
            .build()); 
}
@SwaggerDefinition(tags = {@Tag(name = "app API", description = "Administrative API for app")})
@ApplicationPath(RestApp.BASE_REST_APP_URI)
public class RestApp extends PackagesResourceConfig {
    public static final String BASE_REST_APP_URI = "/api";
    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> classes = new HashSet<>();
        classes.add(AppRestResource.class);
        return classes;
    }
}

如何添加Swagger?

2 个答案:

答案 0 :(得分:1)

首先,我已经解决了此问题。该示例是sample of guice-jersey-swagger

答案 1 :(得分:0)

我不能帮您Guice,但我可以为您其余的问题提供一些指导。

为了配置Swagger,您需要像以下示例一样配置Jersey servlet。我正在使用web.xml,也许有人可以帮助您进行Guice配置。

<servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>sample.app.ws.MyJavaWSApplication</param-value>
    </init-param>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>io.swagger.jaxrs.listing,sample.app.ws</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/v1/*</url-pattern>
</servlet-mapping>

sample.app.ws是包含REST服务的软件包。然后,您需要使用io.swagger.annotations中的注释来使Swagger自动生成文档。这是一个例子:

package sample.app.ws;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import sample.app.model.Book;

@Path("/books")
@Produces(MediaType.APPLICATION_JSON)
@Api(value = "books")
public class BookService {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Creates a book", notes = "", response = Response.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successful creation"),
            @ApiResponse(code = 500, message = "Resource could not be created")
    })
    public Response add(Book book) {
        // Implementation code
    }
}

为了访问文档,您可以使用Swagger UI生成漂亮的页面,如this。我尝试使用runtime 'org.webjars:swagger-ui:2.1.4'而非couldn't get it working进行此操作,所以最终下载了该文件夹并将其复制到我的webapp目录中。