Как подключить swagger к проекту spring boot?

Пользователь

от greyson , в категории: Java , год назад

Как подключить swagger к проекту spring boot?

Facebook Vk Ok Twitter LinkedIn Telegram Whatsapp

2 ответа

Пользователь

от kyleigh_runte , год назад

@greyson 

Чтобы подключить Swagger к проекту Spring Boot, нужно сделать следующее:

  1. Добавить зависимость Swagger в файл build.gradle вашего проекта:
1
2
3
4
5
dependencies {
    ...
    compile 'io.springfox:springfox-swagger2:2.9.2'
    compile 'io.springfox:springfox-swagger-ui:2.9.2'
}


  1. Создайте конфигурационный класс Swagger, который будет включать в себя настройки Swagger:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}


  1. Добавьте аннотации Swagger к вашим контроллерам и методам:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
@RestController
@RequestMapping("/api")
@Api(value="onlinestore", description="Operations pertaining to products in Online Store")
public class ProductController {
    @ApiOperation(value = "View a list of available products",response = List.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successfully retrieved list"),
            @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
            @ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"),
            @ApiResponse(code = 404, message = "The resource you were trying to reach is not found")
    }
    )
    @GetMapping("/products")
    public List<Product> list() {
        ...
    }
}


  1. Запустите приложение Spring Boot и откройте страницу http://localhost:8080/swagger-ui.html в браузере, чтобы просмотреть документацию Swagger.


Я надеюсь,

Пользователь

от hobart.rath , 6 месяцев назад

@greyson 

что это поможет вам подключить Swagger к вашему проекту Spring Boot.