Setting Up Swagger 2 with a Spring REST API Using Springfox – 使用Springfox在Spring REST API上设置Swagger 2

最后修改: 2015年 12月 6日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Nowadays, front-end and back-end components often separate a web application. Usually, we expose APIs as a back-end component for the front-end component or third-party app integrations.

现在,前端和后端组件经常将一个网络应用分开。通常情况下,我们将API作为后端组件暴露给前端组件或第三方应用程序的集成。

In such a scenario, it is essential to have proper specifications for the back-end APIs. At the same time, the API documentation should be informative, readable, and easy to follow.

在这种情况下,为后端API制定适当的规范是至关重要的。同时,API文档应该内容丰富,可读性强,易于操作。

Moreover, reference documentation should simultaneously describe every change in the API. Accomplishing this manually is a tedious exercise, so automation of the process was inevitable.

此外,参考文档应该同时描述API的每一个变化。人工完成这一工作是一项乏味的工作,因此这一过程的自动化是不可避免的。

In this tutorial, we’ll look at Swagger 2 for a Spring REST web service, using the Springfox implementation of the Swagger 2 specification. If you are not familiar with Swagger, visit its web page to learn more before continuing with this tutorial.

在本教程中,我们将使用Swagger 2规范的Springfox实现,研究Spring REST网络服务的Swagger 2。如果您不熟悉Swagger,请访问其网页,在继续学习本教程之前了解更多信息。

It’s important to mention that the latest version of Swagger specification, now known as OpenAPI 3.0, is better supported by the Springdoc project and should be used for documenting Spring REST API.

值得一提的是,最新版本的Swagger规范,即现在的OpenAPI 3.0,得到了Springdoc项目更好的支持,应该用于记录Spring REST API

2. Target Project

2.目标项目

The creation of the REST service we will use is not within the scope of this article. If you already have a suitable project, use it. If not, these links are a good place to start:

我们将使用的REST服务的创建不在本文的范围之内。如果你已经有一个合适的项目,请使用它。如果没有,这些链接是一个好的开始。

3. Adding the Maven Dependency

3.添加Maven依赖项

As mentioned above, we will use the Springfox implementation of the Swagger specification. The latest version can be found on Maven Central.

如上所述,我们将使用Swagger规范的Springfox实现。最新版本可以在Maven Central上找到。

To add it to our Maven project, we need a dependency in the pom.xml file:

要把它添加到我们的Maven项目中,我们需要在pom.xml文件中加入一个依赖项。

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>3.0.0</version>
</dependency>

3.1. Spring Boot Dependency

3.1.Spring Boot的依赖性

For the Spring Boot based projects, it’s enough to add a single springfox-boot-starter dependency:

对于基于Spring Boot的项目,只需添加一个springfox-boot-starter依赖关系

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

We can add any other starters we need, with a version managed by the Spring Boot parent:

我们可以添加我们需要的任何其他启动器,其版本由Spring Boot父级管理。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.0</version>
</dependency>

4. Integrating Swagger 2 Into the Project

4.将Swagger 2整合到项目中

4.1. Java Configuration

4.1. Java配置

The configuration of Swagger mainly centers around the Docket bean:

Swagger的配置主要围绕着DocketBean。

@Configuration
public class SpringFoxConfig {                                    
    @Bean
    public Docket api() { 
        return new Docket(DocumentationType.SWAGGER_2)  
          .select()                                  
          .apis(RequestHandlerSelectors.any())              
          .paths(PathSelectors.any())                          
          .build();                                           
    }
}

After defining the Docket bean, its select() method returns an instance of ApiSelectorBuilder, which provides a way to control the endpoints exposed by Swagger.

在定义了Docket Bean之后,其select()方法返回ApiSelectorBuilder的一个实例,该实例提供了一种控制由Swagger暴露的端点的方法。

We can configure predicates for selecting RequestHandlers with the help of RequestHandlerSelectors and PathSelectors. Using any() for both will make documentation for our entire API available through Swagger.

我们可以在RequestHandlerSelectorsPathSelectors的帮助下,配置选择RequestHandler的谓词。对这两者使用any()将使我们整个API的文档通过Swagger获得。

4.2. Configuration Without Spring Boot

4.2.不使用Spring Boot的配置

In plain Spring projects, we need to enable Swagger 2 explicitly. To do so, we have to use the @EnableSwagger2WebMvc on our configuration class:

在普通的Spring项目中,我们需要明确地启用Swagger 2。要做到这一点,我们必须在配置类上使用@EnableSwagger2WebMvc

@Configuration
@EnableSwagger2WebMvc
public class SpringFoxConfig {                                    
}

Additionally, without Spring Boot, we don’t have the luxury of auto-configuration of our resource handlers.

此外,如果没有Spring Boot,我们就没有自动配置资源处理程序的权利。

Swagger UI adds a set of resources that we must configure as part of a class that extends WebMvcConfigurerAdapter and is annotated with @EnableWebMvc:

Swagger UI添加了一组资源,我们必须将其配置为一个类的一部分,该类扩展了WebMvcConfigurerAdapter,并被注解为@EnableWebMvc:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
      .addResourceLocations("classpath:/META-INF/resources/");

    registry.addResourceHandler("/webjars/**")
      .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

4.3. Verification

4.3.验证

To verify that Springfox is working, we can visit this URL in our browser:

为了验证Springfox是否工作,我们可以在浏览器中访问这个URL。

http://localhost:8080/spring-security-rest/api/v2/api-docs

http://localhost:8080/spring-security-rest/api/v2/api-docs

The result is a JSON response with a large number of key-value pairs, which is not very human readable. Fortunately, Swagger provides Swagger UI for this purpose.

其结果是一个包含大量键值对的JSON响应,这对人类来说不是很好读。幸运的是,Swagger提供了Swagger UI来实现这一目的。

5. Swagger UI

5.Swagger UI

Swagger UI is a built-in solution that makes user interaction with the Swagger-generated API documentation much easier.

Swagger UI是一个内置的解决方案,使用户与Swagger生成的API文档的互动变得更加容易。

5.1. Enabling Springfox’s Swagger UI

5.1.启用Springfox的Swagger UI

To use Swagger UI, we need to add an additional Maven dependency:

为了使用Swagger UI,我们需要添加一个额外的Maven依赖项。

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>3.0.0</version>
</dependency>

Now we can test it in our browser by visiting:

现在我们可以在浏览器中通过访问来测试它。

http://localhost:8080/your-app-root/swagger-ui/

http://localhost:8080/your-app-root/swagger-ui/

In our case, by the way, the exact URL will be:

在我们的案例中,顺便说一下,确切的URL将是:

http://localhost:8080/spring-security-rest/api/swagger-ui/

http://localhost:8080/spring-security-rest/api/swagger-ui/

The result should look something like this:

结果应该是这样的。

Screenshot_1

5.2. Exploring Swagger Documentation

5.2.探索Swagger文档

Within Swagger’s response is a list of all controllers defined in our application. Clicking on any of them will list the valid HTTP methods (DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT).

在Swagger的响应中,有一个在我们的应用程序中定义的所有控制器的列表。点击其中任何一个,就会列出有效的HTTP方法(DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT)。

Expanding each method provides additional useful data, such as response status, content-type, and a list of parameters. It is also possible to try each method using the UI.

展开每个方法提供额外的有用数据,如响应状态、内容类型和参数列表。也可以使用用户界面来尝试每个方法。

Swagger’s ability to be synchronized with our code base is crucial. To demonstrate this, we can add a new controller to our application:

Swagger与我们的代码库同步的能力是至关重要的。为了证明这一点,我们可以在我们的应用程序中添加一个新的控制器。

@RestController
public class CustomController {

    @RequestMapping(value = "/custom", method = RequestMethod.POST)
    public String custom() {
        return "custom";
    }
}

Now if we refresh the Swagger documentation, we see custom-controller in the list of controllers. As we know, there is only one method (POST) shown in Swagger’s response.

现在,如果我们刷新Swagger文档,我们会在控制器的列表中看到custom-controller。我们知道,在Swagger的响应中只有一个方法(POST)显示。

6. Spring Data REST

6.Spring Data REST

Springfox provides support for Spring Data REST through its springfox-data-rest library.

Springfox 通过其springfox-data-rest库为Spring Data REST提供支持。

Spring Boot will take care of the auto-configuration if it discovers the spring-boot-starter-data-rest on the classpath.

如果Spring Boot在classpath上发现了spring-boot-starter-data-rest,它将负责自动配置

Now let’s create an entity named User:

现在让我们创建一个名为User的实体。

@Entity
public class User {
    @Id
    private Long id;
    private String firstName;
    private int age;
    private String email;

    // getters and setters
}

Then we’ll create the UserRepository to add CRUD operations on the User entity:

然后我们将创建UserRepository,在User实体上添加CRUD操作。

@Repository
public interface UserRepository extends CrudRepository<User, Long> {
}

Last, we’ll import the SpringDataRestConfiguration class to the SpringFoxConfig class:

最后,我们将把SpringDataRestConfiguration类导入到SpringFoxConfig类。

@EnableSwagger2WebMvc
@Import(SpringDataRestConfiguration.class)
public class SpringFoxConfig {
    //...
}

Note: We’ve used the @EnableSwagger2WebMvc annotation to enable Swagger, as it has replaced the @EnableSwagger2 annotation in version 3 of the libraries.

注意:我们使用@EnableSwagger2WebMvc 注解来启用Swagger,因为它在第三版库中取代了@EnableSwagger2 注解。

Let’s restart the application to generate the specifications for the Spring Data REST APIs:

让我们重新启动应用程序,为Spring Data REST APIs生成规范。

swagger_user_1

We can see that Springfox has generated the specifications for the User entity with HTTP methods like GET, POST, PUT, PATCH, and DELETE.

我们可以看到,Springfox已经为User实体生成了HTTP方法的规范,如GETPOST、PUT、PATCHDELETE。

7. Bean Validations

7.Bean验证

Springfox also supports the bean validation annotations through its springfox-bean-validators library.

Springfox还通过其springfox-bean-validators库支持bean验证注释。

First, we’ll add the Maven dependency to our pom.xml:

首先,我们要在pom.xml中添加Maven的依赖。

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-bean-validators</artifactId>
    <version>2.9.2</version>
</dependency>

Again, if we use Spring Boot, we don’t have to provide the above dependency explicitly.

同样,如果我们使用Spring Boot,我们不需要明确提供上述依赖关系

Next, let’s add a few validation annotations like @NotNull and @Min to the User entity:

接下来,让我们给User实体添加一些验证注释,如@NotNull@Min

@Entity
public class User {
    //...
    
    @NotNull(message = "First Name cannot be null")
    private String firstName;
    
    @Min(value = 15, message = "Age should not be less than 15")
    @Max(value = 65, message = "Age should not be greater than 65")
    private int age;
}

Finally, we’ll import the BeanValidatorPluginsConfiguration class to the SpringFoxConfig class:

最后,我们将把BeanValidatorPluginsConfiguration类导入到SpringFoxConfig类。

@EnableSwagger2
@Import(BeanValidatorPluginsConfiguration.class)
public class SpringFoxConfig {
    //...
}

Let’s take a look at the changes in the API specifications:

让我们来看看API规范的变化。

swagger_user_2

Here, we can observe that the User model has * required on the firstName. Also, the minimum and maximum values are defined for the age.

在这里,我们可以看到,User模型在firstName上有* required。此外,最小最大值是为年龄定义的。

8. Plugin

8.插件

In order to add specific features to the API specifications, we can create a Springfox plugin. A plugin can offer various features, from enriching the models and properties to the custom API listings and defaults.

为了给API规范添加特定功能,我们可以创建一个Springfox插件。一个插件可以提供各种功能,从丰富模型和属性到自定义API列表和默认值。

Springfox supports the plugin creation through its spi module. The spi module provides a few interfaces like the ModelBuilderPlugin, ModelPropertyBuilderPlugin, and ApiListingBuilderPlugin that act as an extensibility hook to implement a custom plugin.

Springfox通过其spi模块支持插件的创建。spi模块提供了一些接口,如ModelBuilderPluginModelPropertyBuilderPluginApiListingBuilderPlugin,作为实现自定义插件的可扩展挂钩。

To demonstrate the capabilities, let’s create a plugin to enrich the email property of the User model. We’ll use the ModelPropertyBuilderPlugin interface and set the values of the pattern and example.

为了演示这些功能,让我们创建一个插件来丰富User模型的email属性。我们将使用ModelPropertyBuilderPlugin接口并设置patternexample的值。

First, let’s create the EmailAnnotationPlugin class and override the supports method to allow any documentation type, such as Swagger 1.2 and Swagger 2:

首先,让我们创建EmailAnnotationPlugin类,并覆盖supports方法,以允许任何文档类型,例如Swagger 1.2和Swagger 2。

@Component
@Order(Validators.BEAN_VALIDATOR_PLUGIN_ORDER)
public class EmailAnnotationPlugin implements ModelPropertyBuilderPlugin {
    @Override
    public boolean supports(DocumentationType delimiter) {
        return true;
    }
}

Then we’ll override the apply method of the ModelPropertyBuilderPlugin to set the values of the builder properties:

然后我们将覆盖apply方法的ModelPropertyBuilderPlugin来设置构建器属性的值。

@Override
public void apply(ModelPropertyContext context) {
    Optional<Email> email = annotationFromBean(context, Email.class);
     if (email.isPresent()) {
        context.getSpecificationBuilder().facetBuilder(StringElementFacetBuilder.class)
          .pattern(email.get().regexp());
        context.getSpecificationBuilder().example("email@email.com");
    }
}

So, the API specifications will show the pattern and example values of the property annotated with the @Email annotation.

因此,API规范将显示用@Email注解的属性的patternexample值。

Next, we’ll add the @Email annotation to the User entity:

接下来,我们将为@Email实体添加User注释。

@Entity
public class User {
    //...

    @Email(regexp=".*@.*\\..*", message = "Email should be valid")
    private String email;
}

Last, we’ll enable the EmailAnnotationPlugin in the SpringFoxConfig class by registering as a bean:

最后,我们将在SpringFoxConfig类中通过注册为Bean来启用EmailAnnotationPlugin

@Import({BeanValidatorPluginsConfiguration.class})
public class SpringFoxConfig {
    //...

    @Bean
    public EmailAnnotationPlugin emailPlugin() {
        return new EmailAnnotationPlugin();
    }
}

Let’s check out the EmailAnnotationPlugin in action:

让我们看看EmailAnnotationPlugin的运行情况。

swagger_user_3

We can see the value of the pattern is the same regex (.*@.*\\..*) from the email property of the User entity.

我们可以看到pattern的值是来自User实体的email属性的相同的重码(.*@.*\.*)。

Similarly, the value of the example (email@email.com) is the same, as defined in the apply method of the EmailAnnotationPlugin.

同样,example(email@email.com)的值也是如此,在EmailAnnotationPluginapply方法中定义。

9. Advanced Configuration

9.高级配置

The Docket bean of our application can be configured to give us more control over the API documentation generation process.

我们的应用程序的DocketBean可以被配置为让我们对API文档生成过程有更多的控制。

9.1. Filtering API for Swagger’s Response

9.1.对Swagger的响应进行过滤的API

It is not always desirable to expose the documentation for the entire API. We can restrict Swagger’s response by passing parameters to the apis() and paths() methods of the Docket class.

暴露整个API的文档并不总是可取的。我们可以通过向Docket类的apis()paths()方法传递参数来限制Swagger的响应。

As seen above, RequestHandlerSelectors allows using the any or none predicates but can also be used to filter the API according to the base package, class annotation, and method annotations.

如上所述,RequestHandlerSelectors允许使用anynone谓词,但也可用于根据基础包、类注释和方法注释来过滤API。

PathSelectors provides additional filtering with predicates, which scan the request paths of our application. We can use any(), none(), regex(), or ant().

PathSelectors通过谓词提供额外的过滤,扫描我们应用程序的请求路径。我们可以使用any(), none(), regex(), 或ant()

In the example below, we will instruct Swagger to include only controllers from a particular package, with specific paths, using the ant() predicate:

在下面的例子中,我们将使用ant()谓词,指示Swagger只包括来自特定包的控制器,并具有特定的路径。

@Bean
public Docket api() {                
    return new Docket(DocumentationType.SWAGGER_2)          
      .select()                                       
      .apis(RequestHandlerSelectors.basePackage("com.baeldung.web.controller"))
      .paths(PathSelectors.ant("/foos/*"))                     
      .build();
}

9.2. Custom Information

9.2.自定义信息

Swagger also provides some default values in its response, which we can customize, such as “Api Documentation”, “Created by Contact Email”, and “Apache 2.0”.

Swagger还在其响应中提供了一些默认值,我们可以对其进行自定义,如 “Api文档”、”由联系人电子邮件创建 “和 “Apache 2.0″。

To change these values, we can use the apiInfo(ApiInfo apiInfo) method — the ApiInfo class that contains custom information about the API:

要改变这些值,我们可以使用apiInfo(ApiInfo apiInfo) 方法–ApiInfo类,它包含关于API的自定义信息。

@Bean
public Docket api() {                
    return new Docket(DocumentationType.SWAGGER_2)          
      .select()
      .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
      .paths(PathSelectors.ant("/foos/*"))
      .build()
      .apiInfo(apiInfo());
}

private ApiInfo apiInfo() {
    return new ApiInfo(
      "My REST API", 
      "Some custom description of API.", 
      "API TOS", 
      "Terms of service", 
      new Contact("John Doe", "www.example.com", "myeaddress@company.com"), 
      "License of API", "API license URL", Collections.emptyList());
}

9.3. Custom Methods Response Messages

9.3.自定义方法的响应信息

Swagger allows globally overriding response messages of HTTP methods through Docket’s globalResponses() method.

Swagger允许通过DocketglobalResponses()方法来全局覆盖HTTP方法的响应信息

First, we need to instruct Swagger not to use default response messages. Suppose we want to override 500 and 403 response messages for all GET methods.

首先,我们需要指示Swagger不要使用默认的响应信息。假设我们想为所有的GET方法覆盖500403响应信息。

To achieve this, some code must be added to the Docket’s initialization block (original code is excluded for clarity):

为了实现这一点,必须在Docket的初始化块中添加一些代码(为了清晰起见,不包括原始代码)。

.useDefaultResponseMessages(false)
.globalResponses(HttpMethod.GET, newArrayList(
    new ResponseBuilder().code("500")
        .description("500 message").build(),
    new ResponseBuilder().code("403")
        .description("Forbidden!!!!!").build()
));

Screenshot_2

10. Swagger UI With an OAuth-Secured API

10.具有OAuth安全的API的Swagger UI

The Swagger UI provides a number of very useful features that we’ve covered well so far here. But we can’t really use most of these if our API is secured and not accessible.

Swagger用户界面提供了许多非常有用的功能,到目前为止我们已经很好地介绍了这些功能。但是,如果我们的API是安全的,不能被访问,我们就不能真正使用其中的大部分功能。

Let’s see how we can allow Swagger to access an OAuth-secured API using the Authorization Code grant type in this example.

让我们看看在这个例子中,我们如何允许Swagger使用授权码授予类型来访问一个OAuth安全的API。

We’ll configure Swagger to access our secured API using the SecurityScheme and SecurityContext support:

我们将配置Swagger以使用SecuritySchemeSecurityContext支持来访问我们的安全API。

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2).select()
        .apis(RequestHandlerSelectors.any())
        .paths(PathSelectors.any())
        .build()
        .securitySchemes(Arrays.asList(securityScheme()))
        .securityContexts(Arrays.asList(securityContext()));
}

10.1. The Security Configuration

10.1.安全配置

We’ll define a SecurityConfiguration bean in our Swagger configuration and set some defaults:

我们将在我们的Swagger配置中定义一个SecurityConfiguration bean,并设置一些默认值。

@Bean
public SecurityConfiguration security() {
    return SecurityConfigurationBuilder.builder()
        .clientId(CLIENT_ID)
        .clientSecret(CLIENT_SECRET)
        .scopeSeparator(" ")
        .useBasicAuthenticationWithAccessCodeGrant(true)
        .build();
}

10.2. SecurityScheme

10.2.SecurityScheme

Next, we’ll define our SecurityScheme; this is used to describe how our API is secured (Basic Authentication, OAuth2, …).

接下来,我们将定义我们的SecurityScheme;这是用来描述我们的API的安全方式(Basic Authentication、OAuth2,…)。

In our case here, we’ll define an OAuth scheme used to secure our Resource Server:

在我们这里,我们将定义一个OAuth方案,用于保护我们的资源服务器

private SecurityScheme securityScheme() {
    GrantType grantType = new AuthorizationCodeGrantBuilder()
        .tokenEndpoint(new TokenEndpoint(AUTH_SERVER + "/token", "oauthtoken"))
        .tokenRequestEndpoint(
          new TokenRequestEndpoint(AUTH_SERVER + "/authorize", CLIENT_ID, CLIENT_SECRET))
        .build();

    SecurityScheme oauth = new OAuthBuilder().name("spring_oauth")
        .grantTypes(Arrays.asList(grantType))
        .scopes(Arrays.asList(scopes()))
        .build();
    return oauth;
}

Note that we used the Authorization Code grant type, for which we need to provide a token endpoint and the authorization URL of our OAuth2 Authorization Server.

注意,我们使用了授权代码授予类型,为此我们需要提供一个令牌端点和我们的OAuth2授权服务器的授权URL。

And here are the scopes we need to have defined:

这里是我们需要定义的作用域。

private AuthorizationScope[] scopes() {
    AuthorizationScope[] scopes = { 
      new AuthorizationScope("read", "for read operations"), 
      new AuthorizationScope("write", "for write operations"), 
      new AuthorizationScope("foo", "Access foo API") };
    return scopes;
}

These sync up with the scopes we actually have defined in our application, for the /foos API.

这些与我们在应用程序中实际定义的作用域同步,用于/foos API。

10.3. SecurityContext

10.3.SecurityContext

Finally, we need to define a SecurityContext for our example API:

最后,我们需要为我们的示例API定义一个SecurityContext

private SecurityContext securityContext() {
    return SecurityContext.builder()
      .securityReferences(
        Arrays.asList(new SecurityReference("spring_oauth", scopes())))
      .forPaths(PathSelectors.regex("/foos.*"))
      .build();
}

Note how the name we used here in the reference — spring_oauth — syncs up with the name we used previously in the SecurityScheme.

请注意我们在这里引用的名字–spring_oauth–与我们之前在SecurityScheme中使用的名字是同步的。

10.4. Test

10.4.测试

Now that we have everything set up and ready to go, let’s take a look at our Swagger UI and try access the Foo API.

现在我们已经设置好了一切,准备就绪,让我们看看我们的Swagger用户界面,并尝试访问Foo API。

We can access the Swagger UI locally:

我们可以在本地访问Swagger用户界面。

http://localhost:8082/spring-security-oauth-resource/swagger-ui.html

As we can see, a new Authorize button now exists due to our security configurations:

我们可以看到,由于我们的安全配置,现在存在一个新的授权按钮。

swagger_1

When we click the Authorize button, we can see the following pop-up to authorize our Swagger UI to access the secured API:

当我们点击授权按钮时,我们可以看到下面的弹出窗口,授权我们的Swagger UI访问安全的API。

swagger_2

Note that:

请注意,。

  • We can already see the CLIENT_ID and CLIENT_SECRET, as we’ve pre-configured them earlier (but we can still change them).
  • We can now select the scopes we need.

Here’s how the secured API is marked:

下面是安全的API是如何标记的。

swagger_3

And now, finally, we can hit our API!

而现在,我们终于可以打出我们的API了!

Of course, it almost goes without saying that we need to be careful how we expose Swagger UI externally, now that this security configuration is active.

当然,不言而喻,既然这个安全配置已经启动,我们就需要小心翼翼地将Swagger UI暴露在外部。

11. Conclusion

11.结论

In this article, we set up Swagger 2 to generate documentation for a Spring REST API. We also explored ways to visualize and customize Swagger’s output. And finally, we looked at a simple OAuth configuration for Swagger.

在这篇文章中,我们设置了Swagger 2来为Spring REST API生成文档。我们还探索了可视化和定制Swagger输出的方法。最后,我们看了Swagger的一个简单的OAuth配置。

The full implementation of this tutorial can be found in the GitHub project. To see the setup in a Boot project, check out this GitHub module.

本教程的完整实现可以在GitHub 项目中找到。要查看 Boot 项目中的设置,请查看 这个 GitHub 模块

For the OAuth section, the code is available in our spring-security-oauth repository.

对于OAuth部分,代码可在我们的spring-security-oauth资源库中找到。

And if you’re a student of REST With Spring, go to Lesson 1 from Module 7 for a deep dive into setting up Swagger with Spring and Spring Boot.

如果您是REST With Spring的学生,请进入模块7的第1课,深入了解用Spring和Spring Boot设置Swagger的情况。