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

How to integrate Swagger into Java project using Guice + Jersey + servlet and generate REST API docs automatically

我有一个使用 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?

我无法在 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. I've tried doing this using runtime 'org.webjars:swagger-ui:2.1.4' but couldn't get it working 这样的漂亮页面,所以我最终下载了文件夹并将其复制到我的 webapp 目录。

首先要感谢,我已经解决了这个问题。样本是 sample of guice-jersey-swagger