Swagger 2.0 (OpenApi 3.0) 中的 BeanConfig(或类似的?)

BeanConfig (or similar?) in Swagger 2.0 (OpenApi 3.0)

我目前正在将我们的 API 文档(Swagger 1.5)迁移到 Swagger 2.0 (OpenApi 3.0)

API 文档是 Swagger 文档,它使用 Maven 包 swagger-annotationsswagger-jaxrs 通过 java 注释生成。我已经用新版本更新了 pom.xml,所以它看起来像:

        <dependency>
            <groupId>io.swagger.core.v3</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>2.0.6</version>
        </dependency>
        <dependency>
            <groupId>io.swagger.core.v3</groupId>
            <artifactId>swagger-jaxrs2</artifactId>
            <version>2.0.6</version>
        </dependency>

而且所有旧注释都被新注释替换(变化很大)并且看起来不错。

问题是我们使用 BeanConfig 定义文档常规配置并自动扫描所有 REST 资源,因此文档在 /swagger.json.

处自动生成

问题 是我找不到 "new way" 创建 BeanConfig 和自动扫描资源这样的事情,所以一切都在 /swagger.json/openapi.json (也许现在是 OpenAPIDefinition 之类的东西?)

如果有人能指出正确的方向,我将不胜感激...

经过一些研究,我可以在他们的 Github for JAX-RS application 中找到一些关于它的文档,所以结果与我所做的类似,但现在不是使用 BeanConfig, 它使用 OpenAPIInfo:

@ApplicationPath("/sample")
public class MyApplication extends Application {

    public MyApplication(@Context ServletConfig servletConfig) {
        super();
        OpenAPI oas = new OpenAPI();
        Info info = new Info()
            .title("Swagger Sample App bootstrap code")
            .description("This is a sample server Petstore server.  You can find out more about Swagger " +
                    "at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).  For this sample, " +
                    "you can use the api key `special-key` to test the authorization filters.")
            .termsOfService("http://swagger.io/terms/")
            .contact(new Contact()
                    .email("apiteam@swagger.io"))
            .license(new License()
                    .name("Apache 2.0")
                    .url("http://www.apache.org/licenses/LICENSE-2.0.html"));

        oas.info(info);
        SwaggerConfiguration oasConfig = new SwaggerConfiguration()
            .openAPI(oas)
            .prettyPrint(true)
            .resourcePackages(Stream.of("io.swagger.sample.resource").collect(Collectors.toSet()));

        try {
            new JaxrsOpenApiContextBuilder()
                .servletConfig(servletConfig)
                .application(this)
                .openApiConfiguration(oasConfig)
                .buildContext(true);
        } catch (OpenApiConfigurationException e) {
            throw new RuntimeException(e.getMessage(), e);
        }

    }
}

尽管 OP 已经回答了他们自己的问题,但是为像我这样登陆此 post 的人添加了更多详细信息,因为我想从 swagger 1.x 迁移到 swagger 2.0(openAPI 3 ) 并且需要完整的配置。

(此示例用于嵌入式码头)

// Jetty configuration

// ContextHandlerCollection contexts

ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/api");
context.addFilter(GzipFilter.class, "/*", EnumSet.allOf(DispatcherType.class));

ResourceConfig resourceConfig = new ResourceConfig(ImmutableSet.<Class<?>>builder()
                                                                .add(MyRestService.class)
                                                                .build());
resourceConfig.registerClasses(OpenApiResource.class,AcceptHeaderOpenApiResource.class); // for swagger, this will cerate openapi.json at <host>/api/openapi.json
context.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/*");
contexts.addHandler(context);   

如果您需要更改默认的 swagger 配置,可以通过 OP 在他们的回答中描述的内容来完成:

OpenAPI oas = new OpenAPI();
        Info info = new Info()
            .title("Swagger Sample App bootstrap code")
            .description("This is a sample server Petstore server.  You can find out more about Swagger " +
                    "at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).  For this sample, " +
                    "you can use the api key `special-key` to test the authorization filters.")
            .termsOfService("http://swagger.io/terms/")
            .contact(new Contact()
                    .email("apiteam@swagger.io"))
            .license(new License()
                    .name("Apache 2.0")
                    .url("http://www.apache.org/licenses/LICENSE-2.0.html"));

        oas.info(info);
        SwaggerConfiguration oasConfig = new SwaggerConfiguration()
            .openAPI(oas)
            .prettyPrint(true)
            .resourcePackages(Stream.of("io.swagger.sample.resource").collect(Collectors.toSet()));

        try {
            new JaxrsOpenApiContextBuilder()
                .servletConfig(servletConfig)
                .application(this)
                .openApiConfiguration(oasConfig)
                .buildContext(true);
        } catch (OpenApiConfigurationException e) {
            throw new RuntimeException(e.getMessage(), e);
        }

对于上述要求,有一个更简单的解决方案。

import io.swagger.v3.jaxrs2.integration.resources.OpenApiResource;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Contact;
import io.swagger.v3.oas.annotations.info.Info;
import org.glassfish.jersey.server.ResourceConfig;


@OpenAPIDefinition(
    info =
        @Info(
            title = "Sample rest service",
            version = "1.0.0",
            description = "Sample rest service",
            contact =
                @Contact(
                    url = "https://jira2.cerner.com/projects/Dey",
                    name = "ADey")))
public class SampleRestApplication extends ResourceConfig {
  public SampleRestApplication() {
    register(OpenApiResource.class);
  }
}

您的服务将在 /openApi.yaml|json.

加载您的 API 规范

同一主题的另一个变体。您可以将 openAPI 配置生成逻辑打包成独立的 class,如下所示:

    @Provider
    public class SwaggerInfoBlackMagic implements Feature {
        @Context ServletConfig config;
        @Context Application app;

        @Override
        public boolean configure(FeatureContext context) {
            //The aim here is to force construction of a (convincing) OpenApiContext before swagger does!
            //This has been lifted from BaseOpenApiResource
            String ctxId = getContextIdFromServletConfig(config);
            try {
                OpenApiContext ctx = new JaxrsOpenApiContextBuilder()
                        .servletConfig(config)
                        .application(app)
                        //Might need more of these depending on your setup..
                        //.resourcePackages(resourcePackages)
                        //.configLocation(configLocation)
                        .openApiConfiguration(getOpenApi())
                        .ctxId(ctxId)
                        .buildContext(true); //this also stores the instance statically
            } catch (OpenApiConfigurationException e) {
                throw new RuntimeException(e);
            }
            return true;
        }


        private OpenAPIConfiguration getOpenApi() {...}
    }

然后当你需要它时,你可以简单地添加:

jersey().register(SwaggerInfoBlackMagic.class);

和上面的一样,但稍微整洁一些。