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

最后修改: 2015年 12月 6日

1. Overview


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.


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.


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.


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


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:


3. Adding the Maven Dependency


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:



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依赖关系


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

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


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:


public class SpringFoxConfig {                                    
    public Docket api() { 
        return new Docket(DocumentationType.SWAGGER_2)  

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.


4.2. Configuration Without Spring Boot

4.2.不使用Spring Boot的配置</strong

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

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:

public void addResourceHandlers(ResourceHandlerRegistry registry) {


4.3. Verification


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




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</strong

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依赖项。


Now we can test it in our browser by visiting:




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




The result should look something like this:



5.2. Exploring Swagger Documentation


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:


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.


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:


public class User {
    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:


public interface UserRepository extends CrudRepository<User, Long> {

Last, we’ll import the SpringDataRestConfiguration class to the SpringFoxConfig 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生成规范。


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


7. Bean Validations


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


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



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:


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:


public class SpringFoxConfig {

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



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


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.


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.


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.


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。

public class EmailAnnotationPlugin implements ModelPropertyBuilderPlugin {
    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:


public void apply(ModelPropertyContext context) {
    Optional<Email> email = annotationFromBean(context, Email.class);
     if (email.isPresent()) {

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


Next, we’ll add the @Email annotation to the 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:


public class SpringFoxConfig {

    public EmailAnnotationPlugin emailPlugin() {
        return new EmailAnnotationPlugin();

Let’s check out the EmailAnnotationPlugin in action:



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


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


9. Advanced Configuration


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


9.1. Filtering API for Swagger’s Response


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.


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.


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:


public Docket api() {                
    return new Docket(DocumentationType.SWAGGER_2)          

9.2. Custom Information


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的自定义信息。

public Docket api() {                
    return new Docket(DocumentationType.SWAGGER_2)          

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

9.3. Custom Methods Response Messages


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


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.


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


.globalResponses(HttpMethod.GET, newArrayList(
    new ResponseBuilder().code("500")
        .description("500 message").build(),
    new ResponseBuilder().code("403")


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.


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


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


public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2).select()

10.1. The Security Configuration


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

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

public SecurityConfiguration security() {
    return SecurityConfigurationBuilder.builder()
        .scopeSeparator(" ")

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:


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

    SecurityScheme oauth = new OAuthBuilder().name("spring_oauth")
    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.


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


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


private SecurityContext securityContext() {
    return SecurityContext.builder()
        Arrays.asList(new SecurityReference("spring_oauth", scopes())))

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


10.4. Test

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:



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



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。


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:



And now, finally, we can hit our 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


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.


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的情况。