Swagger 2.0(OpenApi 3.0)中的BeanConfig(或类似的东西)是什么?

10

我目前正在将我们的API文档(原本是Swagger 1.5版本)迁移到Swagger 2.0 (OpenAPI 3.0)。

这些API文档是使用java注释和maven包swagger-annotationsswagger-jaxrs生成的Swagger文档。我已经更新了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

问题是我找不到“新方法”来创建BeanConfig和自动扫描资源,以便所有内容都可以生成在/swagger.json/openapi.json(现在可能是OpenAPIDefinition之类的东西?)

如果有人能指点我正确的方向,我将非常感激...

4个回答

9

经过一些研究,我在他们的Github上找到了一些关于JAX-RS应用程序的文档,因此结果与我之前所做的类似,但现在不再使用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);
        }

    }
}

4
注意,这里是 io.swagger.v3.oas.models.info.Info,不要和相同名称的注释混淆! - Matthew
1
谢谢@Matthew,实际上将导入添加到Java代码片段中是一个好习惯,从现在开始我会这样做的 :) - Javier Aviles
那么,所有这些都是为了生成swagger.json吗?我认为这就是最初的问题所在,对吧?我使用了这段代码,但是没有为我生成swagger.json文件。 - Alkanshel
是的,一个用于提供Swagger文档的URL会自动生成。 - Javier Aviles

5

虽然OP已经回答了他们自己的问题,但是对于像我这样来到这篇文章寻求从swagger 1.x迁移到swagger 2.0(OpenAPI 3)并需要完整配置的人来说,还需要添加一些细节。

(这个示例是针对嵌入式jetty的)

// 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);
        }

你如何将这两个示例结合在一起?即,你从哪里获取ServletConfig或contexts对象? - Sloloem
该对象将是您Jetty配置的一部分。与Swagger无关的任何内容。 - tryingToLearn
@tryingToLearn 我正在使用 Jetty 11(即 Jakarta EE 9),并添加了所需的依赖项,但无法找到 GzipFilter.class 以进行 context.addFilter(GzipFilter.class, "/*", EnumSet.allOf(DispatcherType.class)); - a13e
@AniruddhaTekade,你可以忽略那一行。 - tryingToLearn

2
以上要求有一个更简单的解决方案。
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-3配置Swagger-Core。您有关于如何将其集成到Jetty 11中的任何想法吗? - a13e
如果值是常量,这个方法就可行 - 在这种情况下,将它们放入 openapi-configuration.yaml 文件中会更简单! - Matthew
这是针对Glassfish特定的内容... - Alkanshel

0

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

    @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);

这与上面的代码相同,但稍微整洁一些。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接